生产者消费者问题

来源:互联网 发布:unity3d和虚幻4 比较 编辑:程序博客网 时间:2024/06/03 12:44
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();        }    }}