-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMain.java
More file actions
43 lines (40 loc) · 1.71 KB
/
Copy pathMain.java
File metadata and controls
43 lines (40 loc) · 1.71 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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
int consumersNumber = 10;
int producersNumber = 5;
DonutStorage donutStorage = new DonutStorage(20);
ExecutorService executor = Executors.newFixedThreadPool(consumersNumber+producersNumber);
List<Future<?>> futures = new ArrayList<>(consumersNumber);
for (int i = 0; i < consumersNumber; i++) {
futures.add(executor.submit(() -> {
Client consumer = new Client(Client.consume, donutStorage);
System.out.println(Thread.currentThread().getName() + " consumed " +
consumer.operate(10));
}));
}
for (int i = 0; i < producersNumber; i++) {
futures.add(executor.submit(() -> {
Client producer = new Client(Client.produce, donutStorage);
System.out.println(Thread.currentThread().getName() + " produced " +
producer.operate(10));
}));
}
executor.shutdown();
// make the main thread wait for others to finish
for (Future<?> future: futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("Exception while getting from future" + e.getMessage());
e.printStackTrace();
}
}
System.out.println("Number of remaining donuts: " + donutStorage.blockingQueue.size());
}
}