使用最简便的方法终止线程。
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)