System.out.println(" ---"+ Thread.currentThread()); } // Set message to stop the thread. mRunner.makeStop(); } } // The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. classRunnerimplementsRunnable { booleanmakeStop =false;...
*/voidstart(){t=newThread(()->{while(!stop){//判断当前线程是否被打断System.out.println("正在监控系统...");try{Thread.sleep(3*1000L);//执行 3 秒System.out.println("任务执行 3 秒");System.out.println("监控的系统正常!");}catch(InterruptedException e){System.out.println("任务执行被中...
voidstop(){ stop =true; t.interrupt(); } } 在这里我们先创建了一个SystemMonitor类作为系统检测器,每3秒一循环的进行检测,考虑到在Thread.currentThread().isInterrupted()可能在某些情况下中断失效,所以我们这里自定义一个stop变量,作为线程中断的标识,检测线程启动先对标识位进行判断。 然后,我们在Test类中写...
stop = true; t.interrupt(); } } 在这里我们先创建了一个SystemMonitor类作为系统检测器,每3秒一循环的进行检测,考虑到在Thread.currentThread().isInterrupted()可能在某些情况下中断失效,所以我们这里自定义一个stop变量,作为线程中断的标识,检测线程启动先对标识位进行判断。 然后,我们在Test类中写一个测试方法...
public class WrongStopThread extends Thread { public static void main(String[] main) { WrongStopThread wrongStopThread = new WrongStopThread(); wrongStopThread.setName("myThread"); System.out.println("线程开始启动..."); wrongStopThread.start(); try ...
3.使用stop方法终止线程 程序中可以直接使用thread.stop()来强行终止线程,但是stop方法是很危险的,就象突然关闭计算机电源,而不是按正常程序关机一样,可能会产生不可预料的结果,不安全主要是:thread.stop()调用之后,创建子线程的线程就会抛出ThreadDeatherror的错误,并且会释放子线程所持有的所有锁。一般任何进行加锁的...
stop 1??false stop 2??false 类Run.java中虽然是在thread对象上调用以下代码:thread.interrupt(), 后面又使用 System.out.println("stop 1??" + thread.interrupted()); System.out.println("stop 2??" + thread.interrupted()); 来判断thread对象所代表的线程是否停止,但从控制台打印的结果来看,线程并未...
因此,在这里强烈建议大家不要再用stop方法去停止线程了! 如何优雅的停止一个线程 我们知道线程只有从 runnable 状态(可运行/运行状态) 才能进入terminated 状态(终止状态),如果线程处于 blocked、waiting、timed_waiting 状态(休眠状态),就需要通过 Thread 类的 interrupt() 方法,让线程从休眠状态进入 runnable 状态,从...
在上面的代码中,使用一个boolean类型的标识符flag来控制线程的执行,通过调用stopThread()方法来将flag设置为false,从而停止线程。 2. 使用interrupt()方法 另一个替代方法是使用Thread的interrupt()方法。在线程的循环中检查线程是否被中断,如果被中断则退出循环,从而停止线程。下面是一个示例代码: ...
private volatile boolean stopping = false; /** * 修改取消线程的标志位 */ public void stop() ...