-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
49 lines (36 loc) · 1.36 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
package com.codecafe.concurrency._atomic;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
class Task implements Runnable {
private final Semaphore semaphore;
private final AtomicIntegerRoundRobin atomicIntegerRoundRobin;
public Task(Semaphore semaphore, AtomicIntegerRoundRobin atomicIntegerRoundRobin) {
this.semaphore = semaphore;
this.atomicIntegerRoundRobin = atomicIntegerRoundRobin;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " - " + atomicIntegerRoundRobin.index());
Thread.sleep(1000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
AtomicIntegerRoundRobin atomicIntegerRoundRobin = new AtomicIntegerRoundRobin(5);
// create a batch of 3 threads at a time
Semaphore semaphore = new Semaphore(3);
ExecutorService executor = Executors.newFixedThreadPool(50);
IntStream.range(1, 50).forEach(i -> executor.execute(new Task(semaphore, atomicIntegerRoundRobin)));
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}
}