使用定時器2秒後終止一個執行緒
阿新 • • 發佈:2019-02-02
使用最簡便的方法終止執行緒。
class Thread1 extends Thread{
private int count = 5;
private String name;
public Thread1(String name) {
this.name=name;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name + "執行 count= " + count--);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return; //此時在丟擲異常後直接退出
}
}
}
public static void main(String[] args) {
Thread mTh1=new Thread1("A");
mTh1.start();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("定時器此時執行");
mTh1.interrupt(); //2秒後中止執行緒的執行,並在執行緒的run方法中收集異常並退出。
}
}, 2000);
}
}
輸出:
A執行 count= 5
A執行 count= 4
定時器此時執行
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at Thread1.run(Thread1.java:17)