forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT21.java
More file actions
50 lines (40 loc) · 1.48 KB
/
T21.java
File metadata and controls
50 lines (40 loc) · 1.48 KB
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
package com.basic;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.*;
/**
* @program JavaBooks
* @description: 利用容器LinkedBlockingQueue生产者消费者
* @author: mf
* @create: 2019/12/31 22:26
*/
public class T21 {
// private static Queue<String> strs = new ConcurrentLinkedDeque<>();
// private static BlockingQueue<String> strs = new ArrayBlockingQueue<>(10); // 有界队列
// private static LinkedTransferQueue<String> strs = new LinkedTransferQueue<>(); // 更高的高并发,先找消费者
private static BlockingQueue<String> strs = new LinkedBlockingDeque<>(); // 无界队列
private static Random r = new Random();
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
strs.put("a" + i);
TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "p1").start();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
for (;;) {
try {
System.out.println(Thread.currentThread().getName() + " take -" + strs.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "c" + i).start();
}
}
}