-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestForStampedLock.java
99 lines (83 loc) · 2.99 KB
/
TestForStampedLock.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.concurrent.TimeUnit;
import com.hui.stamped.pac.StampedLock;
public class TestForStampedLock {
/**
* @param args
*/
public static void main(String[] args) throws InterruptedException{
// TODO Auto-generated method stub
StampedLock lock = new StampedLock();
new Thread(new WriteThread(lock)).start();
// new Thread(new ReadThreadTry(lock)).start();
Thread.sleep(200);
new Thread(new ReadThreadTry(lock)).start();
Thread.sleep(100);
// new Thread(new ReadThreadTry(lock)).start();
for( int i = 0; i < 6; ++i)
new Thread(new ReadThread(lock)).start();
Thread.sleep(300);
for( int i = 0; i < 6; ++i)
new Thread(new WriteThreadLast(lock)).start();
}
private static class WriteThread implements Runnable{
private StampedLock lock;
public WriteThread(StampedLock lock){
this.lock = lock;
}
public void run(){
long writeLong = lock.writeLock();
System.out.println(Thread.currentThread().getName() + " WRITE");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlockWrite(writeLong);
}
}
private static class ReadThreadTry implements Runnable{
private StampedLock lock;
public ReadThreadTry(StampedLock lock){
this.lock = lock;
}
public void run(){
long readLong = 0;
try {
readLong = lock.tryReadLock(600, TimeUnit.MILLISECONDS);
if(readLong > 0)
System.out.println(Thread.currentThread().getName() + " READ LOCK");
else
System.out.println(Thread.currentThread().getName() + " READ noLOCK");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(readLong>0)
lock.unlockRead(readLong);
}
}
}
private static class ReadThread implements Runnable{
private StampedLock lock;
public ReadThread(StampedLock lock){
this.lock = lock;
}
public void run(){
long readLong = lock.readLock();
System.out.println(Thread.currentThread().getName() + " READ");
lock.unlockRead(readLong);
}
}
private static class WriteThreadLast implements Runnable{
private StampedLock lock;
public WriteThreadLast(StampedLock lock){
this.lock = lock;
}
public void run(){
long writeLong = lock.writeLock();
System.out.println(Thread.currentThread().getName() + " WRITE");
lock.unlockWrite(writeLong);
}
}
}