java多線程之生產者-消費者使用Object的wait()和notify()方法實現

package com.zhong.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用 wait,notify 實現生產消費者
 */
public class Stock {

    private volatile int maxnum = 10;   //最大的容量通知消費者
    private volatile int minmun = 0;    //最小的容量通知生產者
    private String name; //定義倉庫中存在的內容
    private List<String> contain = new ArrayList<String>();


    public synchronized void putOne(String name) {

        while (contain.size() > maxnum) {//如果倉庫中的容量大於最大容量進行線程等待
            try {
                this.wait();//線程等待 等待消費者消費
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(1000);
            this.name = name;
            contain.add(name);
            System.out.println("生產者:" + Thread.currentThread().getName() + "生產了" + name + ",消費者趕緊來消費");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.notifyAll();//喚醒所有線程
        }


    }

    public synchronized void getOne() {
        while (contain.size() <= minmun) {
            try {
                this.wait();//線程等待 等待生產者生產
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消費者:" + Thread.currentThread().getName() + "消費了" + contain.get(0) + ",生產者趕緊生產");
        contain.remove(0);

        this.notifyAll();//喚起
    }

    public static void main(String[] args) {

        Stock s = new Stock();
        Get get = new Get(s);
        Put put = new Put(s);
        Get get1 = new Get(s);
        Put put1 = new Put(s);

        //多個生產者和消費者對緩存區進行拿放數據
        get.start();
        put.start();
        get1.start();
        put1.start();


    }
}

/**
 * 消費者
 */
class Get extends Thread {
    private Stock s;//緩衝區

    public Get(Stock s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            s.getOne();
        }
    }
}

/**
 * 生產者
 */
class Put extends Thread {
    private Stock s;//緩衝區

    public Put(Stock s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            s.putOne("mac");
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章