生產消費者同步容器

生產消費者同步容器

利用wait(),notifyAll(),方法交替生產和消費容器內變量,利用同步鎖實現同步容器

/**
 * @ClassName:MyContainer
 * @Description:TODO使用wait(),notifyAll(),編寫生產者消費者容器,get,put方法,2個生產線程
 * 10個消費線程
 * @Author:ZY
 * @Date:2019/6/24 0024 23:23
 * @Version:1.0
 **/
public class MyContainer<T> {
    //非靜態容器
    final LinkedList<T> containList = new LinkedList<T>();
    private Integer count = 0;
    private static final Integer MAX = 100;

    public synchronized void put(T t) {
        while (containList.size() == MAX) {
            try {
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        containList.add(t);
        ++count;
        this.notifyAll();
    }

    public synchronized T get() {
        while (containList.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        T t = containList.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {
        final MyContainer<String> container = new MyContainer<String>();
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int i1 = 0; i1 < 500; i1++) {
                        container.put(Thread.currentThread().getName() + i1);
                    }
                }
            },"product" + i).start();
        }
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int i1 = 0; i1 < 100; i1++) {
                        System.out.println(container.get());
                    }
                }
            },"consumer" + i).start();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章