public class TestArrayBlockingQueue {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
for(int i =0;i<2;i++){
final int num = i;
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
queue.put(num);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
Integer a = queue.take();
System.out.println("a = " + a);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
ArrayBlockingQueue
最新推荐文章于 2024-12-12 15:49:55 发布
本文通过一个具体示例展示了如何使用Java并发包中的ArrayBlockingQueue。该示例创建了一个容量为3的阻塞队列,并启动了两个线程用于向队列中添加元素,同时启动了一个线程用于从队列中取出并打印元素。此过程循环进行,演示了ArrayBlockingQueue的基本用法。
1158

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



