package concurrentTest; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class TestBlockingQueue { public static void main(String[] args) { final BlockingQueue<Integer> queue=new LinkedBlockingQueue<Integer>(3); final Random random=new Random(); class Producer implements Runnable{ public void run() { while(true){ try { int i=random.nextInt(100); queue.put(i);//当队列达到容量时候,会自动阻塞的 System.out.println("put "+ i + " into queue"); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable{ public void run() { while(true){ try { System.out.println("consumer:" + queue.take());//当队列为空时,也会自动阻塞 Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } new Thread(new Producer()).start(); new Thread(new Consumer()).start(); } }
BlockingQueue
最新推荐文章于 2024-09-22 16:37:50 发布
本文通过一个具体的示例程序,展示了如何使用Java中的BlockingQueue接口实现生产者消费者模式。该模式中,生产者不断地向队列中添加随机生成的整数,而消费者则从队列中取出这些整数进行消费。当队列满时,生产者的添加操作会被阻塞;当队列空时,消费者的取数操作也会被阻塞。
2591

被折叠的 条评论
为什么被折叠?



