-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronizedDefect.java
More file actions
41 lines (37 loc) · 1.18 KB
/
SynchronizedDefect.java
File metadata and controls
41 lines (37 loc) · 1.18 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
package chapter05;
import java.util.concurrent.TimeUnit;
/**
* Created by zhangzhao on 2018/8/23.
*/
// synchronized 的缺点:
// 1.无法控制阻塞时长(无法确定什么时候或去到monitor的lock)
// 2.阻塞不可被中断(比如 阻塞了1个小时候,不想等待了,没办法只能等)
public class SynchronizedDefect {
public synchronized void syncMethod(){
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
SynchronizedDefect defect = new SynchronizedDefect();
Thread t1 = new Thread(defect::syncMethod,"T1");
t1.start();
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(defect::syncMethod,"T2");
t2.start();
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.interrupt();
System.out.println(t2.isInterrupted());
System.out.println(t2.getState());
}
}