-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaitNotify.java
54 lines (47 loc) · 1.4 KB
/
WaitNotify.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
import java.util.ArrayList;
public class WaitNotify {
public static void main(String[] args) {
BlockingQueue queue = new BlockingQueue();
Thread worker = new Thread(new Runnable() {
public void run() {
while (true) {
Runnable task = queue.get();
task.run();
}
}
});
worker.start();
for (int i = 0; i < 11; i++){
queue.put(getTask());
}
}
public static Runnable getTask() {
return new Runnable() {
@Override
public void run() {
System.out.println("started: "+this);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println("finish: "+this);
}
};
}
static class BlockingQueue {
ArrayList<Runnable> tasks = new ArrayList<>();
public synchronized Runnable get(){
while (tasks.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {}
}
Runnable task = tasks.get(0);
tasks.remove(task);
return task;
}
public synchronized void put(Runnable task){
tasks.add(task);
notify();
}
}
}