Java 学习笔记之 Return停止线程

Return停止线程:

使用interrupt()和return结合也可以实现停止线程的效果。不过还是建议使用“抛异常“的方法,因为在catch块中可以将异常向上抛,使线程停止的事件得以传播。

public class ReturnInterruptThread extends Thread{
    @Override
    public void run() {
        while (true){
            if (this.isInterrupted()){
                System.out.println("Stop thread.");
                return;
            }
            System.out.println("timer=" + System.currentTimeMillis());
        }
    }
}

public class ThreadRunMain {
    public static void main(String[] args) {
        testReturnInterruptThread();

    }
    public static void testReturnInterruptThread(){
        try {
            ReturnInterruptThread rit = new ReturnInterruptThread();
            rit.start();
            Thread.sleep(2000);
            rit.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

原文地址:https://www.cnblogs.com/AK47Sonic/p/7670668.html