怎么停止一个线程

说明:
Thread里面的stop,suspend,resume,已经被弃用,这里不做讨论。

1.使用interrupt()方法:

package com.concurrece.demo;

public class MyRunnable implements Runnable {

    public void run() {
        for (int i=0;i<10000;i++){
            System.out.println(i);
        }

    }
}

package com.concurrece.demo;

public class InterruptDemo {

    public static void main(String[] args) throws InterruptedException {
       Thread thread = new Thread(new MyRunnable());
        thread.start();
        thread.sleep(500);
        thread.interrupt();
        boolean interrupted = thread.interrupted();
        System.out.println("看看是否停止:"+interrupted);
        System.out.println(thread.interrupted());
    }
}

上面代码运行结果
查看上图可知thread.interrupt()方法并没有停止线程,使用这个方法并不像for 里面break一样,立刻中止循环,而是给当前线程打了一个标记,并不是真正的停止线程。
那怎么在后续判断线程是不是停止状态呢?
this.interrupted():测试当前线程是否已经中断,并且会清楚当前线程的中断状态。
当前线程可以是main函数,可以用Thread.currentThread().interrupt()测试是否中断

this.isInterrupted():测试线程Thread对象是否已经是中断状态,它不能清除线程的中断状态。

利用停止状态去判断然后做出相应的措施:
可以在线程执行run方法里面判断当前是否是终止状态,再让代码return;则后面的代码不会再执行

return法:

package com.concurrece.demo;

public class MyRunnable implements Runnable {

    public void run() {

        for (int i=0;i<10000;i++){
            boolean b = Thread.currentThread().isInterrupted();
            if(b){
                return;
            }
            System.out.println(i);
        }

        System.out.println("如果我执行 说明线程没有被停止");
    }
}

抛异常法:

package com.concurrece.demo;

public class MyRunnable implements Runnable {

    public void run() {

        try {
            for (int i=0;i<10000;i++){
                boolean b = Thread.currentThread().isInterrupted();
                if(b){
                    //return;
                    throw new InterruptedException();
                }
                System.out.println(i);
            }
            System.out.println("如果我执行 说明线程没有被停止");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

如果在线程sleep()的时候调用interrupt()方法 或者 反过来都会引起代码抛出InterruptedException异常。

发布了23 篇原创文章 · 获赞 5 · 访问量 4845

猜你喜欢

转载自blog.csdn.net/weixin_42567141/article/details/103728269
今日推荐