Java线程通信-生产者与消费者简单实例(一)


1.产品类

//产品
public class Product {
    public Product(){
        System.out.print("生产了一个产品");
    }
}

2.生产者类

//生产者
public class Producer implements Runnable{
    int COUNT_MAX;                      //仓库大小
    private LinkedList<Product> list;   //仓库
    public Producer(LinkedList<Product> list,int COUNT_MAX){
        this.list = list;
        this.COUNT_MAX = COUNT_MAX;
    }

    @Override
    public void run() {
        //不断的生产产品放入仓库
        for(;;){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (list){
                while(list.size() >= COUNT_MAX){     //仓库满时等待
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.push(new Product());
                System.out.println(",还剩下: "+list.size()+"个");
                list.notifyAll();   //唤醒消费者消费
            }
        }
    }
}

3.消费者类

//消费者
public class Consumer implements Runnable {
    private LinkedList<Product> list;
    public Consumer(LinkedList<Product> list){
        this.list = list;
    }
    @Override
    public void run() {
        for(;;){
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //不断从仓库消费产品
            synchronized (list){
                while(list.size() <= 0){//仓库没有产品时等待
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.pop();
                System.out.println("消费了一个产品,剩: "+list.size()+"个");
                list.notifyAll();   //消费产品后唤醒生产者
            }

        }
    }
}

4.测试

    @Test
    public void Test(){
        LinkedList<Product> list = new LinkedList<Product>();
        Consumer consumer = new Consumer(list);
        Producer producer = new Producer(list,10);

        new Thread(consumer).start();
        new Thread(consumer).start();
        new Thread(producer).start();
        new Thread(producer).start();
        new Thread(producer).start();
        new Thread(producer).start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

文章作者: Bryson
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bryson !
评论
 上一篇
下一篇 
  目录