-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathWaitNotifyQueue.java
89 lines (80 loc) · 2.21 KB
/
WaitNotifyQueue.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
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
86
87
88
89
package br.com.leonardoz.patterns.condition_queues;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Pattern: Wait/Notify Queue
*
* Motivations: State dependent classes can be difficult to implement, mainly
* because some precondition states can become true through another thread.
* Condition Queues help us to identify the condition predicates and do
* control to programming flux associated with it.
*
* Intent: Create a Wait/Notify mechanism based on the capabilities of each java
* object to be a condition queue itself.
*
* Applicability: State dependent algorithms used in concurrent programming.
*
*/
public class WaitNotifyQueue {
private boolean continueToNotify;
private BlockingQueue<String> messages;
public WaitNotifyQueue(List<String> messages) {
this.messages = new LinkedBlockingQueue<>(messages);
this.continueToNotify = true;
}
public synchronized void stopsMessaging() {
continueToNotify = false;
notifyAll();
}
public synchronized void message() throws InterruptedException {
while (!continueToNotify)
wait();
var message = messages.take();
System.out.println(message);
}
public static void main(String[] args) {
var messages = new LinkedList<String>();
for (int i = 0; i < 130; i++) {
messages.add(UUID.randomUUID().toString());
}
var waitNotifyQueue = new WaitNotifyQueue(messages);
new Thread(() -> {
try {
while (true) {
waitNotifyQueue.message();
Thread.sleep(300);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}).start();
var random = new Random();
new Thread(() -> {
while (true) {
int val = random.nextInt(100);
System.out.println(val);
if (val == 99) {
break;
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
waitNotifyQueue.stopsMessaging();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}).start();
}
}