1、使用Interrupt来通知
while (!Thread.currentThread().isInterrupted() && more work to do) { do more work }
首先通过 Thread.currentThread().isInterrupt() 判断线程是否被中断,随后检查是否还有工作要做。
public class StopThread implements Runnable { @Override public void run() { int count = 0; while (!Thread.currentThread().isInterrupted() && count < 1000) { System.out.println("count = " + count++); } } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new StopThread()); thread.start(); Thread.sleep(5); thread.interrupt(); } }
2、使用volatile标志一个字段,通过判断这个字段true/false退出线程
/** * 描述: 演示用volatile的局限:part1 看似可行 */ public class WrongWayVolatile implements Runnable { private volatile boolean canceled = false; @Override public void run() { int num = 0; try { while (num <= 100000 && !canceled) { if (num % 100 == 0) { System.out.println(num + "是100的倍数。"); } num++; Thread.sleep(1); } } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { WrongWayVolatile r = new WrongWayVolatile(); Thread thread = new Thread(r); thread.start(); Thread.sleep(5000); r.canceled = true; } }
以上就是java停止线程的方式,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。