-
Notifications
You must be signed in to change notification settings - Fork 122
/
Main.java
56 lines (48 loc) · 1.09 KB
/
Main.java
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
package multithreads.waitAndNotify;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
var q = new TaskQueue();
var ts = new ArrayList<Thread>();
for (int i = 0; i < 5; i++) {
var t = new Thread() {
public void run() {
// 执行task:
while (true) {
String s = q.getTask();
System.out.println("execute task: " + s);
}
}
};
t.start();
ts.add(t);
}
var add = new Thread(
() -> {
for (int i = 0; i < 10; i++) {
// 放入task:
String s = "t-" + Math.random();
System.out.println("add task: " + s);
q.addTask(s);
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
);
add.start();
try {
add.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (var t : ts) {
t.interrupt();
}
}
}