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

2021-03-26  本文已影响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
...
上一篇 下一篇

猜你喜欢

热点阅读