File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
src/com/winterbe/java8/samples/concurrent Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments