生產者消費者問題

package 生產者消費者;

import java.util.ArrayList;
import java.util.LinkedList;

public class ProducerConsumerPattern {
    //定義緩衝區最大容量
    public static final int MAX_CAPACITY=5;
    //LinkedList當緩衝區
    static LinkedList<Object> list=new LinkedList<Object>();
    static class Producer implements Runnable{
        @Override
        public void run() {
            while(true){
                synchronized (list){
                    while (list.size()==MAX_CAPACITY){
                        System.out.println("當前產品個數爲:"+list.size()+"等待生產者生產。。");
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    System.out.println("當前產品個數:"+list.size());
                    list.add(new Object());
                    System.out.println("生產了一個產品,當前產品個數爲:"+list.size());
                    list.notifyAll();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //消費者
    static class Consumer implements Runnable{
        @Override
        public void run() {
            while (true){
                synchronized (list){
                    while (list.size()==0){
                        System.out.println("當前產品數量爲 :"+list.size()+"等待生產者生產");
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("當前產品個數爲:"+list.size());
                    list.remove();
                    System.out.println("消費了一個產品,當前產品個數爲:"+list.size());
                    list.notifyAll();
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        for (int i=0;i<3;i++){
            new Thread(new Producer()).start();
        }
        for (int i = 0; i <3 ; i++) {
            new Thread(new Consumer()).start();
        }
    }
}

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