forked from janzolau1987/study-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterrupted.java
More file actions
48 lines (44 loc) · 1.22 KB
/
Interrupted.java
File metadata and controls
48 lines (44 loc) · 1.22 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
package com.yaoyaohao.study.thread;
import java.util.concurrent.TimeUnit;
/**
* 理解线程中断
*
* @author liujianzhu
* @date 2016年7月18日 下午10:36:26
*
*/
public class Interrupted {
public static void main(String[] args) throws Exception{
//sleepThread不停的尝试睡眠
Thread sleepThread = new Thread(new SleepRunner(),"SleepThread");
sleepThread.setDaemon(true);
//busyThread不停的运行
Thread busyThread = new Thread(new BusyRunner(),"BusyThread");
busyThread.setDaemon(true);
sleepThread.start();
busyThread.start();
//休眠5秒,让sleepThread和busyThread充分运行
TimeUnit.SECONDS.sleep(5);
sleepThread.interrupt();
busyThread.interrupt();
//
System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted());
System.out.println("BusyThread interrupted is " + busyThread.isInterrupted());
//防止sleepThread和busyThread立刻退出
SleepUtils.second(2);
}
static class SleepRunner implements Runnable {
@Override
public void run() {
while(true){
SleepUtils.second(10);
}
}
}
static class BusyRunner implements Runnable {
@Override
public void run() {
while(true){}
}
}
}