-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadInterrupt.java
More file actions
47 lines (41 loc) · 1.26 KB
/
ThreadInterrupt.java
File metadata and controls
47 lines (41 loc) · 1.26 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
package org.cp;
/**
* create by CP on 2019/7/29 0029.
*/
public class ThreadInterrupt {
private static Object o = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(10000);//Thread的今天方法
} catch (InterruptedException e) {
System.out.println("Thread 1 被打断");
e.printStackTrace();
}
});
thread1.start();
Thread thread2 = new Thread(() -> {
synchronized (o) {//wait()方法一定要在synchronized里面调用
try {
o.wait();//Object的方法,同步监视器(锁)对象调用
} catch (InterruptedException e) {
System.out.println("Thread 2 被打断");
e.printStackTrace();
}
}
});
thread2.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.interrupt();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.interrupt();
}
}