美文网首页
[Java编程] - 生产消费模型

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

作者: 夹胡碰 | 来源:发表于2021-03-26 10:04 被阅读0次
直接上代码
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();
        }
    }
}
输出
...
custom-0 118279
custom-2 118278
custom-2 118281
custom-2 118282
custom-2 118283
custom-1 118277
custom-1 118285
...

相关文章

网友评论

      本文标题:[Java编程] - 生产消费模型

      本文链接:https://www.haomeiwen.com/subject/xzfjhltx.html