Skip to content

Commit 4022255

Browse files
committed
Add Semaphore example
1 parent eac9257 commit 4022255

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

src/com/winterbe/java8/samples/concurrent/Synchronized1.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static void main(String[] args) {
1919
}
2020

2121
private static void testSyncIncrement() {
22-
count = 1;
22+
count = 0;
2323

2424
ExecutorService executor = Executors.newFixedThreadPool(2);
2525

@@ -32,7 +32,7 @@ private static void testSyncIncrement() {
3232
}
3333

3434
private static void testNonSyncIncrement() {
35-
count = 1;
35+
count = 0;
3636

3737
ExecutorService executor = Executors.newFixedThreadPool(2);
3838

@@ -51,4 +51,5 @@ private static synchronized void incrementSync() {
5151
private static void increment() {
5252
count = count + 1;
5353
}
54+
5455
}

0 commit comments

Comments
 (0)