在java中有以下3种方法可以终止正在运行的线程:
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
- 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。
因为stop不安全:stop会解除由线程获取的所有锁定,当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,假如一个线程正在执行:synchronized void { x = 3; y = 4;} 由于方法是同步的,多个线程访问时总能保证x,y被同时赋值,而如果一个线程正在执行到x = 3;时,被调用了 stop()方法,即使在同步块中,它也会马上stop了,这样就产生了不完整的残废数据。
-
interrupt状态停止线程 和 抛出异常停止线程
调用interrupt方法是在当前线程中打了一个停止标志,并不是真的停止线程。
1. 判断线程是否停止状态
Thread.java类中提供了两种方法:
this.interrupted():
测试当前线程是否已经中断;
- this.isInterrupted():
测试线程是否已经中断;
public class MyThread extends Thread {
public void run(){
super.run();
for(int i=0; i<500000; i++){
if(this.interrupted()) {
System.out.println("线程已经终止, for循环不再执行");
return;
// 或者,抛出异常
// throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
}
}
public class Run {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
…
i=202053
i=202054
i=202055
i=202056
线程已经终止, for循环不再执行