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怎麼停止線程的詳細內容。更多資訊請關注PHP中文網其他相關文章!