-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
57 lines (51 loc) · 955 Bytes
/
Copy pathMain.java
File metadata and controls
57 lines (51 loc) · 955 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package concurrentLock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter{
private Lock lock = new ReentrantLock();
private int value = 0;
public void add(int m){
lock.lock();
try{
this.value += m;
} finally{
lock.unlock();
}
}
public void dec(int m){
lock.lock();
try{
this.value -= m;
} finally{
lock.unlock();
}
}
public int get() {
return value;
}
}
public class Main {
final static int LOOP = 10000;
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread() {
public void run(){
for (int i = 0; i < LOOP; i++){
counter.add(1);
}
}
};
Thread t2 = new Thread() {
public void run(){
for (int i = 0; i < LOOP; i++){
counter.dec(1);
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}