Skip to content

Commit bbf062d

Browse files
committed
Semaphore example
1 parent f61cd1b commit bbf062d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.winterbe.java8.samples.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.Semaphore;
6+
import java.util.concurrent.TimeUnit;
7+
import java.util.stream.IntStream;
8+
9+
/**
10+
* @author Benjamin Winterberg
11+
*/
12+
public class Semaphore2 {
13+
14+
private static Semaphore semaphore = new Semaphore(5);
15+
16+
public static void main(String[] args) {
17+
ExecutorService executor = Executors.newFixedThreadPool(10);
18+
19+
IntStream.range(0, 10)
20+
.forEach(i -> executor.submit(Semaphore2::doWork));
21+
22+
ConcurrentUtils.stop(executor);
23+
}
24+
25+
private static void doWork() {
26+
boolean permit = false;
27+
try {
28+
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
29+
if (permit) {
30+
System.out.println("Semaphore acquired");
31+
ConcurrentUtils.sleep(5);
32+
} else {
33+
System.out.println("Could not acquire semaphore");
34+
}
35+
} catch (InterruptedException e) {
36+
throw new IllegalStateException(e);
37+
} finally {
38+
if (permit) {
39+
semaphore.release();
40+
}
41+
}
42+
}
43+
44+
}

0 commit comments

Comments
 (0)