File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Chapter_30/exercise_30_04 Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ package exercise_30_04 ;
2+
3+ import java .util .concurrent .ExecutorService ;
4+ import java .util .concurrent .Executors ;
5+
6+ public class Exercise_30_04 {
7+ private int sum = new Integer (0 );
8+
9+ public Exercise_30_04 (boolean isSynchronized ) {
10+ ExecutorService executor = Executors .newCachedThreadPool ();
11+ for (int i = 0 ; i < 1000 ; i ++) {
12+ if (isSynchronized ) {
13+ executor .execute (new SynchronizedSumTask ());
14+ }
15+ else {
16+ executor .execute (new SumTask ());
17+ }
18+ }
19+
20+ executor .shutdown ();
21+
22+ while (!executor .isTerminated ()) {
23+ }
24+ }
25+
26+ private class SumTask implements Runnable {
27+
28+ @ Override
29+ public void run () {
30+ increaseSum ();
31+ }
32+ }
33+
34+ private class SynchronizedSumTask implements Runnable {
35+
36+ @ Override
37+ public void run () {
38+ increaseSumWithSync ();
39+ }
40+ }
41+
42+ public void increaseSum () {
43+ sum ++;
44+ }
45+
46+ public synchronized void increaseSumWithSync () {
47+ sum ++;
48+ }
49+
50+ public static void main (String [] args ) {
51+ Exercise_30_04 sumTestWithoutSync = new Exercise_30_04 (false );
52+ Exercise_30_04 sumTestWithSync = new Exercise_30_04 (true );
53+
54+ System .out .println ("The sum without synchronization is: " + sumTestWithoutSync .sum );
55+ System .out .println ("The sum with synchronization is: " + sumTestWithSync .sum );
56+ }
57+ }
You can’t perform that action at this time.
0 commit comments