-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReentrantLockDemo.java
More file actions
50 lines (39 loc) · 1.24 KB
/
ReentrantLockDemo.java
File metadata and controls
50 lines (39 loc) · 1.24 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
package kb.concurrent.lock;
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.stream.IntStream;
class Counter implements Runnable {
private static int count = 0;
Lock lock = null;
public Counter(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
try {
lock.lock();
// This is not atomic operation
count++;
} finally {
lock.unlock();
}
}
public static int getCount() {
return count;
}
}
public class ReentrantLockDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Lock lock = new ReentrantLock();
final int numberOfThreads = 100;
IntStream.range(0, numberOfThreads).forEach((i -> executor.execute(new Counter(lock))));
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
// The count should be equal of the number of threads: 100
System.out.println(Counter.getCount());
}
}