File tree 2 files changed +54
-2
lines changed
src/com/winterbe/java8/samples/concurrent
2 files changed +54
-2
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 Semaphore1 {
13
+
14
+ private static final int NUM_INCREMENTS = 10000 ;
15
+
16
+ private static Semaphore semaphore = new Semaphore (1 );
17
+
18
+ private static int count = 0 ;
19
+
20
+ public static void main (String [] args ) {
21
+ testIncrement ();
22
+ }
23
+
24
+ private static void testIncrement () {
25
+ ExecutorService executor = Executors .newFixedThreadPool (2 );
26
+
27
+ IntStream .range (0 , NUM_INCREMENTS )
28
+ .forEach (i -> executor .submit (Semaphore1 ::increment ));
29
+
30
+ ConcurrentUtils .stop (executor );
31
+
32
+ System .out .println ("Increment: " + count );
33
+ }
34
+
35
+ private static void increment () {
36
+ boolean permit = false ;
37
+ try {
38
+ permit = semaphore .tryAcquire (5 , TimeUnit .SECONDS );
39
+ count ++;
40
+ }
41
+ catch (InterruptedException e ) {
42
+ throw new RuntimeException ("could not increment" );
43
+ }
44
+ finally {
45
+ if (permit ) {
46
+ semaphore .release ();
47
+ }
48
+ }
49
+ }
50
+
51
+ }
Original file line number Diff line number Diff line change @@ -19,7 +19,7 @@ public static void main(String[] args) {
19
19
}
20
20
21
21
private static void testSyncIncrement () {
22
- count = 1 ;
22
+ count = 0 ;
23
23
24
24
ExecutorService executor = Executors .newFixedThreadPool (2 );
25
25
@@ -32,7 +32,7 @@ private static void testSyncIncrement() {
32
32
}
33
33
34
34
private static void testNonSyncIncrement () {
35
- count = 1 ;
35
+ count = 0 ;
36
36
37
37
ExecutorService executor = Executors .newFixedThreadPool (2 );
38
38
@@ -51,4 +51,5 @@ private static synchronized void incrementSync() {
51
51
private static void increment () {
52
52
count = count + 1 ;
53
53
}
54
+
54
55
}
You can’t perform that action at this time.
0 commit comments