基于线程池的事件通知的生产者与消费者

基于线程池的事件通知的生产者与消费者

/**
 * 基于线程池的事件通知的生产者与消费者
 * @Author: mihuajun 【kobe96688@126.com】
 * @Date: 12/9/2018 10:22 AM
 */
public class ThreadPoolProducerConsumerDemo {
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        LinkedList<Integer> queue = new LinkedList<>();

        executorService.execute(() -> {
            for (int i = 0; i < 100; i++) {
                synchronized (queue) {
                    if (queue.size() == 5) {
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(50L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    queue.add(i);
                    System.out.println("add:"+i);
                    queue.notify();

                }
            }
        });

        executorService.execute(() -> {
            while (true){
                synchronized (queue){
                    if (queue.size() == 0){
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    try {
                        Thread.sleep(50L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Integer item = queue.pop();
                    System.out.println("remove:"+item);
                    queue.notify();
                }
            }
        });


    }
}

要点:
  1. 带删除的集合应该用LinkedList之类的存储结构
  2. 线程应该由线程池管理线程应该由线程池管理
  3. 线程的nofity(),wait()需要一个公共对象的锁持有synchronized (queue)
  4. 线程的notify()可以直接唤醒阻塞的线程
  5. 线程的wait()可以当前线程等待的同时,释放所持有对象的锁
  6. 除非调用wait(),queue 对象在synchronized代码块执行完才会释放锁
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值