-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockLearningB2.java
More file actions
60 lines (41 loc) · 1.06 KB
/
Copy pathLockLearningB2.java
File metadata and controls
60 lines (41 loc) · 1.06 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
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockLearningB2 {
public static void main(String[] args) {
PhoneB2 phoneB2 = new PhoneB2();
new Thread(()->{
phoneB2.sms();
},"A").start();
new Thread(()->{
phoneB2.sms();
},"B").start();
}
}
class PhoneB2{
Lock lock = new ReentrantLock();
public void sms() {
lock.lock(); //细节问题 两把锁
//锁必须配对,否则就会死在里面
try {
System.out.println(Thread.currentThread().getName() + "sms");
call();
}
catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void call()
{
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "call");
}
catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}