Java如何停止线程

思路为:
在调用thread.start()方法之后,调用thread.interrupt()方法来中断这个线程。在thread的run()方法中,运行之前要检查本线程是否被中断(用this.interrupted()this.isInterrupted(),前者为静态方法,感觉没什么区别),如果被中断,则要throw一个InterruptedException,从而导致run()方法停止运行,转到catch语句。

示例代码 如下:
MyThread类

public class MyThread extends Thread {

    @Override
    public void run(){
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.isInterrupted()) { //检测是否被中断
                    System.out.println("I has been interrupted, I will go away");
                    throw  new InterruptedException(); //抛异常
                }
                System.out.println("i: " + i);
            }
            System.out.print("this is sentence after for loop");
        }
        catch(InterruptedException ie){//捕获异常
            System.out.print("this is catch clause");
        }
    }

}

运行测试类Run:

public class Run {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myThread.interrupt();//中断这个线程

        System.out.print("end");

    }
}

关于this.interrupted()this.inInterrupted()检测方法的说明,
前者为测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能,连续调用时,第二次检测结果为false;
后者测试线程Thread对象是否已经是中断状态,不清楚标志。

另外,如何停止一个正在休眠(正在sleep()方法中)的线程?,调用sleep方法时,必须显式捕获InterruptException。sleep()方法在检测到异常时会自动抛出中断异常,

thread.interrupt()会使isInterruped()标志为true,从而可以捕获异常。
thread.stop()会抛出java.lang.ThreadDeath异常,stop方法已经过期,不应该被使用

参考《Java多线程编程核心技术》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值