-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightLockB.java
More file actions
67 lines (47 loc) · 1.41 KB
/
Copy pathEightLockB.java
File metadata and controls
67 lines (47 loc) · 1.41 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
/*
8锁 就是八个锁的问题
3、 增加了一个普通方法 没有synchronized 先发短信还是hello? 先hello然后发短信
原因:hello没有上锁 不是同步方法 不受锁的影响
4、两个对象 两个同步方法 先call 后send 锁的是方法调用者 有两个调用者 互相不影响
A延迟了4秒 A慢一点
*/
import java.sql.Time;
import java.util.concurrent.TimeUnit;
public class EightLockB {
public static void main(String[] args) {
Phone2 phone=new Phone2();
Phone2 phone2=new Phone2();
//两个对象
new Thread(()->{
phone.sendSms();},"A").start();
try{
TimeUnit.SECONDS.sleep(1);} //阻塞main线程
catch(InterruptedException e){
e.printStackTrace();
}
new Thread(()->{
phone2.hello();},"B").start();
}
}
class Phone2
{
//synchronized的对象是方法的调用者
//两个方法用的是同一个锁,谁先拿到谁执行 A先拿到锁
//
public synchronized void sendSms()
{
try {
TimeUnit.SECONDS.sleep(4);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("sendSms");
}
public synchronized void call()
{
System.out.println("call");
}
public void hello(){ //没有synchronized
System.out.println("hello");
}
}