Java 学习笔记之 Return停止线程

mac2022-06-30  56

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

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)