forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCounterWithLock.java
More file actions
51 lines (37 loc) · 1.43 KB
/
Copy pathCounterWithLock.java
File metadata and controls
51 lines (37 loc) · 1.43 KB
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
42
43
44
45
46
47
48
49
50
51
package modern.challenge;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;
public class CounterWithLock {
private static final Logger logger = Logger.getLogger(CounterWithLock.class.getName());
private static final Lock lock = new ReentrantLock();
private static int count;
public void counter() {
lock.lock();
try {
count++;
// logger.info(() -> "Count value: " + count
// + " | Thread: " + Thread.currentThread().getName());
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
System.setProperty("java.util.logging.SimpleFormatter.format",
"[%1$tT] [%4$-7s] %5$s %n");
CounterWithLock counterWithLock = new CounterWithLock();
Runnable task = () -> {
counterWithLock.counter();
};
ExecutorService executor = Executors.newFixedThreadPool(8);
for (int i = 0; i < 1_000_000; i++) {
executor.execute(task);
}
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
logger.info(() -> "Final result: " + count);
}
}