forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronizedCounter.java
More file actions
41 lines (26 loc) · 917 Bytes
/
SynchronizedCounter.java
File metadata and controls
41 lines (26 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.zetcode;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class SynchronizedCounter {
private int counter = 0;
// synchronized method
public synchronized void inc() {
counter = counter + 1;
}
public int get() {
return counter;
}
}
public class SynchronizedCounterEx {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
var synchronizedCounter = new SynchronizedCounter();
for (int i = 0; i < 50; i++) {
executorService.submit(() -> synchronizedCounter.inc());
}
executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Final value: " + synchronizedCounter.get());
}
}