在java语言中,可以使用stop()方法和suspend()方法来终止线程的执行.
当使用Thread.stop()来终止线程时,它会释放已经锁定的所有监视资源,具有不安全性
suspend()方法不会释放锁,容易发生死锁(两个或者两个以上进程在执行过程中,因争夺资源而造成进程间互相等待的现象,如果无外力干涉,它们将无法推进)问题
鉴于以上两种方法的不安全性,java语言已经不建议使用以上两种方法来终止线程了
思想:
让线程自行进入Dead状态,如果想要停止一个线程的执行,就提供某种方式让线程自动结束run()方法的执行
方法①:
通过设置一个flag标志来控制循环是否执行
public class MyThread implements Runnable{
pirvate volatile Boolean flag;
public void stop(){
flag=false;
}
public void run(){
while(flag){
.......
}
}
}
方法②
上面的方法存在问题,当线程处于非运行状态时(当sleep()方法被调用或者当wait()方法被调用或者当被I/O阻塞时),上面的方法就不能用了.此时可以通过interrupt()方法来打破阻塞的情况,当interrupt()方法被调用时,会抛出InterruptedException异常,可以通过run()方法捕获这个异常来让线程安全退出
public class MyThread{
public static void main(String [] args){
Thread thread=new Thread(new Runnable(){
public void run(){
System.out.println(“thread go to sleep”);
try{
//使用线程休眠模拟线程被阻塞
Thread.sleep(5000);
}catch(InterruptedException e){
System.out.println(“thread is interrupted”);
}
}
});
thread.start();
thread.interrupt();
}
}
输出结果为:
thread go to sleep
thread is interrupted