-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain2.java
More file actions
68 lines (59 loc) · 1.16 KB
/
Copy pathMain2.java
File metadata and controls
68 lines (59 loc) · 1.16 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package concurrentLock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Counter2 {
private ReadWriteLock lock = new ReentrantReadWriteLock();
private Lock rlock = lock.readLock();
private Lock wlock = lock.writeLock();
private int value = 0;
public void add(int m){
wlock.lock();
try{
this.value += m;
}finally{
wlock.unlock();
}
}
public void dec(int m){
wlock.lock();
try{
this.value -= m;
}finally{
wlock.unlock();
}
}
public int get() {
rlock.lock();
try{
return value;
} finally{
rlock.unlock();
}
}
}
public class Main2 {
final static int LOOP = 100;
public static void main(String[] args) throws InterruptedException {
Counter counter2 = new Counter();
Thread t1 = new Thread() {
public void run(){
for (int i = 0; i < LOOP; i++){
counter2.add(1);
}
}
};
Thread t2 = new Thread() {
public void run(){
for (int i = 0; i < LOOP; i++){
counter2.dec(1);
}
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter2.get());
}
}