终止线程的方法

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值