BlockingQueue实现阻塞队列

时间:2022-03-21 17:37:04
 1 import java.util.concurrent.ArrayBlockingQueue;
2 import java.util.concurrent.BlockingQueue;
3
4 public class BlockingQueueTest {
5 public static void main(String[] args) {
6 final BlockingQueue queue = new ArrayBlockingQueue(3); //队列长度
7 for(int i=0;i<2;i++){
8 new Thread(){
9 public void run(){
10 while(true){
11 try {
12 Thread.sleep((long)(Math.random()*1000));
13 System.out.println(Thread.currentThread().getName() + "准备放数据!");
14 queue.put(1); //放数据
15 System.out.println(Thread.currentThread().getName() + "已经放了数据," +
16 "队列目前有" + queue.size() + "个数据");
17 } catch (InterruptedException e) {
18 e.printStackTrace();
19 }
20
21 }
22 }
23
24 }.start();
25 }
26
27 new Thread(){
28 public void run(){
29 while(true){
30 try {
31 //将此处的睡眠时间分别改为100和1000,观察运行结果
32 Thread.sleep(1000);
33 System.out.println(Thread.currentThread().getName() + "准备取数据!");
34 queue.take(); //取数据
35 System.out.println(Thread.currentThread().getName() + "已经取走数据," +
36 "队列目前有" + queue.size() + "个数据");
37 } catch (InterruptedException e) {
38 e.printStackTrace();
39 }
40 }
41 }
42
43 }.start();
44 }
45 }
测试如下:

Thread-1准备放数据!Thread-1已经放了数据,队列目前有1个数据
Thread
-0准备放数据!
Thread
-0已经放了数据,队列目前有2个数据
Thread
-2准备取数据!
Thread
-2已经取走数据,队列目前有1个数据
Thread
-1准备放数据!
Thread
-1已经放了数据,队列目前有2个数据
Thread
-0准备放数据!
Thread
-0已经放了数据,队列目前有3个数据
Thread
-1准备放数据!