前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Java编程] - 生产消费模型

[Java编程] - 生产消费模型

作者头像
夹胡碰
发布2021-03-27 17:35:44
2830
发布2021-03-27 17:35:44
举报
文章被收录于专栏:程序猿~
直接上代码
代码语言:javascript
复制
public class Test43 {

    private static BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
    private static Random r = new Random();

    public static void main(String[] args) {
        new Thread(() -> {
            AtomicInteger atomicInteger = new AtomicInteger();
            for (;;) {
                try {
                    blockingQueue.put(atomicInteger.getAndIncrement());
                    //Thread.sleep(r.nextInt(100)); 可以不加
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "producer").start();

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (;;){
                    try {
                        System.out.println(Thread.currentThread().getName() + " " + blockingQueue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "consumer-" + i).start();
        }
    }
}
输出
代码语言:javascript
复制
...
custom-0 118279
custom-2 118278
custom-2 118281
custom-2 118282
custom-2 118283
custom-1 118277
custom-1 118285
...
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 直接上代码
  • 输出
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档