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

Commite98f201

Browse files
committed
Atomic accumulate
1 parente8cc2fc commite98f201

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

‎src/com/winterbe/java8/samples/concurrent/Atomic1.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
importjava.util.concurrent.ExecutorService;
44
importjava.util.concurrent.Executors;
55
importjava.util.concurrent.atomic.AtomicInteger;
6+
importjava.util.function.IntBinaryOperator;
67
importjava.util.stream.IntStream;
78

89
/**
@@ -12,23 +13,43 @@ public class Atomic1 {
1213

1314
privatestaticfinalintNUM_INCREMENTS =10000;
1415

15-
privatestaticAtomicIntegercount =newAtomicInteger(0);
16+
privatestaticAtomicIntegeratomicInt =newAtomicInteger(0);
1617

1718
publicstaticvoidmain(String[]args) {
1819
testIncrement();
20+
testAccumulate();
21+
}
22+
23+
privatestaticvoidtestAccumulate() {
24+
atomicInt.set(0);
25+
26+
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
27+
28+
IntStream.range(0,NUM_INCREMENTS)
29+
.forEach(i -> {
30+
Runnabletask = () -> {
31+
IntBinaryOperatoroperator = (a,b) ->a +b;
32+
atomicInt.accumulateAndGet(i,operator);
33+
};
34+
executor.submit(task);
35+
});
36+
37+
ConcurrentUtils.stop(executor);
38+
39+
System.out.format("Accumulate: %d\n",atomicInt.get());
1940
}
2041

2142
privatestaticvoidtestIncrement() {
22-
count.set(0);
43+
atomicInt.set(0);
2344

2445
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
2546

2647
IntStream.range(0,NUM_INCREMENTS)
27-
.forEach(i ->executor.submit(count::incrementAndGet));
48+
.forEach(i ->executor.submit(atomicInt::incrementAndGet));
2849

2950
ConcurrentUtils.stop(executor);
3051

31-
System.out.format("Expected=%d; Is=%d",NUM_INCREMENTS,count.get());
52+
System.out.format("Increment:Expected=%d; Is=%d\n",NUM_INCREMENTS,atomicInt.get());
3253
}
3354

3455
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp