Java实现生产者/消费者模式

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumerTest {
    public static void main(String[] args) {
        final Queue<Integer> sharedQueue = new LinkedList<>();
        Thread producer = new Producer(sharedQueue);
        Thread consumer = new Consumer(sharedQueue);
        producer.start();
        consumer.start();
    }

    static class Producer extends Thread {

        private static final int MAX_QUEUE_SIZE = 5;

        private  final  Queue sharedQueue;

        public Producer(Queue<Integer> sharedQueue) {
            super();
            this.sharedQueue = sharedQueue;
        }

        @Override
        public void run() {
            for(int i=0;i<100;i++){
                synchronized (sharedQueue){
                    while(sharedQueue.size() >= MAX_QUEUE_SIZE){
                        System.out.println("队列满了,等待消费");
                        try{
                           // wait方法调用后立刻释放对象锁
                            sharedQueue.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    sharedQueue.add(i);
                    System.out.println("进行生产:"+i);
                    sharedQueue.notify();
                }
            }
        }
    }
    static class Consumer extends Thread {


        private  final  Queue sharedQueue;

        public Consumer(Queue<Integer> sharedQueue) {
            super();
            this.sharedQueue = sharedQueue;
        }

        @Override
        public void run() {
             while (true){
                 synchronized (sharedQueue){
                     while(sharedQueue.size()==0){
                         try{
                             System.out.println("队列空了,等待生产");
                             // wait方法调用后立刻释放对象锁
                             sharedQueue.wait();
                         }catch(InterruptedException e){
                             e.printStackTrace();
                         }
                     }
                     int number = (int) sharedQueue.poll();
                     System.out.println("进行消费 : " + number );
                     sharedQueue.notify();
                 }
             }
        }
    }
}

这段代码做了下面几件事:

1.定义了一个生产者类,一个消费者类。

2.生产者类循环100次,向同步队列当中插入数据。

3.消费者循环监听同步队列,当队列有数据时拉取数据。

4.如果队列满了(达到5个元素),生产者阻塞。

5.如果队列空了,消费者阻塞。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值