import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class InterruptSetDemoTest {
public static void main(String[] args) {
//创建一个线程t让它睡眠十秒
final Thread t = new Thread(new Runnable(){
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(10);
System.out.println("AAAAAAAAAAAAAAA");
} catch (InterruptedException e) {
System.out.println("线程"+Thread.currentThread().getName()+"被打断...");
e.printStackTrace();
}
System.out.println("BBBBBBBBBBBBBBBBBB");
}},"t");
t.start();
//创建一个计时器,延迟三秒后把线程t打断
final Timer timer = new Timer("计时器");
final boolean[] isstop = new boolean[]{false};
timer.schedule(new TimerTask() {//TimerTask实现了Runnable接口
@Override
public void run() {
t.interrupt();
isstop[0] = true;
}
},1000*3);//延迟三秒执行,delay - 执行任务前的延迟时间,单位是毫秒。
//创建后台程序t1,进行秒钟的显示,以查看进度
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
int count=0;
while(true){
if(!isstop[0]){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(++count+"秒");
}else{
timer.cancel();
}
}
}});
t1.setDaemon(true);
t1.start();
}
}
/**
* 运行结果:
1秒
2秒
线程t被打断...
BBBBBBBBBBBBBBBBBB
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:298)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:328)
at thread2.Test2$1.run(Test2.java:14)
at java.lang.Thread.run(Thread.java:619)
3秒
*/
interrupt()、setDemo()和Timer的简单示例
最新推荐文章于 2021-03-10 11:36:44 发布