JAVA 停止线程:interrupt()和标记

提出问题

当线程阻塞时(如:调用 sleep() 方法休眠),无法停止线程,因为线程在休眠

解决

调用 interrupt() 方法,让休眠的线程抛出异常,在 catch 代码块中 修改标记

java

线程类

package day21;

public class S9中断Interrupt extends Thread{

    private boolean flag = true;

    @Override
    public void run() {
        while( flag ){
            System.out.println("执行run() 方法");
            try {
                System.out.println("开始休眠");
                Thread.sleep(1000000L);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                flag = false;
            }
        }

        System.out.println("线程结束!");
    }




}

测试类

package day21;

public class S9Test {

    public static void main(String[] args) {
        S9中断Interrupt thread = new S9中断Interrupt();
        thread.start();
        thread.interrupt();
    }
}

原文出处:https://malaoshi.top/show_1IX3cE9Dn0C4.html