-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterruptDemo.java
More file actions
34 lines (32 loc) · 1010 Bytes
/
InterruptDemo.java
File metadata and controls
34 lines (32 loc) · 1010 Bytes
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
package ThreadDemo;
/**
* @author:Gerry
* @description:使用interrupt()方法终止线程
* @date: Created in 2018/12/21
*/
public class InterruptDemo extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("已经是停止状态了!我要退出了!");
// break; //使用break无法停止线程
return; //使用return停止线程
}
System.out.println("i=" + (i + 1));
}
System.out.println("看到这句话说明线程并未终止------");
}
public static void main(String[] args) {
try {
InterruptDemo thread = new InterruptDemo();
thread.start();
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException ex) {
System.out.println("main catch");
ex.printStackTrace();
}
}
}