线程的最佳停止方式是使用interrupt方法
该方法会对线程发出停止的通知,但是不会强制停止线程的运行,如果使用stop方法是会强制停止线程的运行,在很多时候有可能或产生脏数据
用法如下:
public class StopThreadTest implements Runnable{ public void run() { int num = 0; while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2){ if (num % 10000 == 0) { System.out.println(num+" 是10000的倍数"); } num++; } System.out.println("任务执行完毕"); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new StopThreadTest()); thread.start(); Thread.sleep(1000); thread.interrupt(); } }
当线程调用了interrupt方法之后,线程会收到中断的通知,我们通知使用Thread.currentThread().isInterrupted()方法来判断线程是否收到中断通知来控制线程的结束.
相比于stop方法,此方法更加的灵活