hooyantsing's Blog

20_BlockingQueue四组API

字数统计: 444阅读时长: 2 min
2020/08/27

20 BlockingQueue四组API

狂神说Java JUC并发编程最新版通俗易懂

队列,先入先出(FIFO)。

四组 API

|添加 |add() |offer()|put() |offer(,,)|
|移除 |remove() |poll() |take()|poll(,) |
|检测队首元素|element()|peek() |- |- |

案例

测试四种 入队 出队 方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
// test1();
// test2();
// test3();
test4();
}

/**
* 抛出异常
*/
public static void test1() {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
System.out.println(queue.add("a"));
System.out.println(queue.add("b"));
System.out.println(queue.add("c"));
// java.lang.IllegalStateException: Queue full 队列满
// System.out.println(queue.add("d"));
System.out.println("------------");
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
// java.util.NoSuchElementException 队列空
// System.out.println(queue.remove());
}

/**
* 返回值 队满返回 false , 队空返回 null
*/
public static void test2() {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
System.out.println(queue.offer("a"));
System.out.println(queue.offer("b"));
System.out.println(queue.offer("c"));
// return false
// System.out.println(queue.offer("d"));
System.out.println("------------");
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
// return null
// System.out.println(queue.poll());
}

/**
* 阻塞
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
queue.put("a");
queue.put("b");
queue.put("c");
// 阻塞,程序不会停止
// queue.put("d");
System.out.println("------------");
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
// 阻塞,程序不会停止
// System.out.println(queue.take());
}

/**
* 阻塞,超时等待
*/
public static void test4() throws InterruptedException {
ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
System.out.println(queue.offer("a"));
System.out.println(queue.offer("b"));
System.out.println(queue.offer("c"));
// 阻塞状态等待 2s ,然后 return false
// System.out.println(queue.offer("d",2, TimeUnit.SECONDS));
System.out.println("------------");
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
// 阻塞状态等待 2s ,然后 return null
// System.out.println(queue.poll(2, TimeUnit.SECONDS));
}
}
CATALOG
  1. 1. 20 BlockingQueue四组API
    1. 1.0.1. 四组 API
    2. 1.0.2. 案例