Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4022255

Browse files
committed
Add Semaphore example
1 parenteac9257 commit4022255

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+
packagecom.winterbe.java8.samples.concurrent;
2+
3+
importjava.util.concurrent.ExecutorService;
4+
importjava.util.concurrent.Executors;
5+
importjava.util.concurrent.Semaphore;
6+
importjava.util.concurrent.TimeUnit;
7+
importjava.util.stream.IntStream;
8+
9+
/**
10+
* @author Benjamin Winterberg
11+
*/
12+
publicclassSemaphore1 {
13+
14+
privatestaticfinalintNUM_INCREMENTS =10000;
15+
16+
privatestaticSemaphoresemaphore =newSemaphore(1);
17+
18+
privatestaticintcount =0;
19+
20+
publicstaticvoidmain(String[]args) {
21+
testIncrement();
22+
}
23+
24+
privatestaticvoidtestIncrement() {
25+
ExecutorServiceexecutor =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+
privatestaticvoidincrement() {
36+
booleanpermit =false;
37+
try {
38+
permit =semaphore.tryAcquire(5,TimeUnit.SECONDS);
39+
count++;
40+
}
41+
catch (InterruptedExceptione) {
42+
thrownewRuntimeException("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
privatestaticvoidtestSyncIncrement() {
22-
count =1;
22+
count =0;
2323

2424
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
2525

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

3434
privatestaticvoidtestNonSyncIncrement() {
35-
count =1;
35+
count =0;
3636

3737
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
3838

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp