Skip to content

Commit 7d733df

Browse files
committed
commit Exercise_30_04
1 parent e314a20 commit 7d733df

File tree

1 file changed

+57
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)