forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphore2.java
More file actions
44 lines (36 loc) · 1.18 KB
/
Semaphore2.java
File metadata and controls
44 lines (36 loc) · 1.18 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
44
package com.winterbe.java8.samples.concurrent;
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;
/**
* @author Benjamin Winterberg
*/
public class Semaphore2 {
private static Semaphore semaphore = new Semaphore(5);
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
IntStream.range(0, 10)
.forEach(i -> executor.submit(Semaphore2::doWork));
ConcurrentUtils.stop(executor);
}
private static void doWork() {
boolean permit = false;
try {
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
if (permit) {
System.out.println("Semaphore acquired");
ConcurrentUtils.sleep(5);
} else {
System.out.println("Could not acquire semaphore");
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} finally {
if (permit) {
semaphore.release();
}
}
}
}