-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadTest.java
54 lines (48 loc) · 1.87 KB
/
ThreadTest.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.LinkedList;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class ThreadTest {
private static final Logger log = Logger.getGlobal();
private static final int MAX_ITEMS = 200;
private static final Queue<Integer> sharedQueue = new LinkedList<>();
private static final ExecutorService executorService = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
CompletableFuture<Void> producerFuture = CompletableFuture.runAsync(() -> {
//sharedQueue.add(1);
for (int i = 1; i <= MAX_ITEMS; i++) {
synchronized (sharedQueue) {
sharedQueue.add(i);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, executorService);
CompletableFuture<Void> consumerFuture = CompletableFuture.runAsync(() -> {
while (!sharedQueue.isEmpty()) {
synchronized (sharedQueue) {
if (!sharedQueue.isEmpty()) {
int item = sharedQueue.poll();
log.info("Popped: " + item);
// Simulate some work being done
} else {
log.info("Empty");
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, executorService);
CompletableFuture<Void> allOf = CompletableFuture.allOf(producerFuture, consumerFuture);
// Block until both tasks are completed
allOf.join();
executorService.shutdown();
}
}