-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathTryLock.java
More file actions
73 lines (67 loc) · 2.39 KB
/
Copy pathTryLock.java
File metadata and controls
73 lines (67 loc) · 2.39 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
69
70
71
72
73
package ch3.s1;
import java.util.concurrent.locks.ReentrantLock;
public class TryLock implements Runnable {
// 这里书中没有提到,这儿使用static,所以创建两个TryLock对象才会共用lock1和lock2
// 如果没有static会很快结束程序,因为使用的是自己的lock1和lock2不会互相锁住
public static ReentrantLock lock1 = new ReentrantLock();
public static ReentrantLock lock2 = new ReentrantLock();
int lock;
public TryLock(int lock) {
this.lock = lock;
}
public void run() {
if (lock == 1) {
while (true) {
if(lock1.tryLock()){
try {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock2.tryLock()) {
try {
System.out.println(Thread.currentThread().getId() + " my job done");
return;
} finally {
lock2.unlock();
}
}
}finally {
lock1.unlock();
}
}
}
} else {
while (true) {
if(lock2.tryLock()){
try {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock1.tryLock()) {
try {
System.out.println(Thread.currentThread().getId() + " my job done");
return;
} finally {
lock1.unlock();
}
}
}finally {
lock2.unlock();
}
}
}
}
}
public static void main(String [] args){
TryLock lock1 = new TryLock(1);
TryLock lock2 = new TryLock(2);
Thread t1 = new Thread(lock1);
Thread t2 = new Thread(lock2);
t1.start();
t2.start();
}
}