public class Test { public static void main(String[] args){ //创建一个阻塞队列,边界为1 BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1); new Thread(new PThread(queue)).start(); new Thread(new CThread(queue)).start(); }} /** * 生产者 */class PThread implements Runnable { private BlockingQueue<String> queue; private AtomicInteger count = new AtomicInteger(); public PThread(BlockingQueue<String> queue) { this.queue = queue; } @Override public void run() { while (true) { String data = count.getAndIncrement() + ""; System.out.println("生产数据:"+data); try { queue.put(data); Thread.sleep(2000);//sleep,便于观察 } catch (InterruptedException e) { e.printStackTrace(); } } }} /** * 消费者 */class CThread implements Runnable { private BlockingQueue<String> queue; public CThread(BlockingQueue<String> queue) { this.queue = queue; } @Override public void run() { while (true) { try { String data = queue.take(); System.out.println("消费数据:"+data); } catch (InterruptedException e) { e.printStackTrace(); } } }}
因为ArrayBlockingQueue是一个阻塞的有界队列,可以直接使用它.
原文地址:https://www.cnblogs.com/z-qinfeng/p/9728842.html
时间: 2024-11-11 19:18:22