import java.util.concurrent.TimeUnit; /** * ThreadTest */ public class ThreadTest implements Runnable { private volatile boolean stop = false; @Override public void run() { while (!stop) { System.out.println(Thread.currentThread().getName() + " is running..."); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { System.out.println("wake up from block"); stop = true; } } System.out.println(Thread.currentThread().getName() + " is exiting..."); } public static void main(String[] args) { ThreadTest threadTest = new ThreadTest(); Thread t1 = new Thread(threadTest); t1.start(); try { TimeUnit.MILLISECONDS.sleep(3000); } catch (InterruptedException e) { // } // 一、使用 volatile共享變量 threadTest.stop = true; // 二、使用interrupt方法 System.out.println("Interrupt thread:" + t1.getName()); t1.interrupt(); try { TimeUnit.MILLISECONDS.sleep(3000); } catch (InterruptedException e) { // } System.out.println("Stopping application..."); } }
2種可能的運行結果:java
Thread-0 is running... Thread-0 is running... Thread-0 is running... Interrupt thread:Thread-0 Thread-0 is running... wake up from block Thread-0 is exiting... Stopping application...
或app
Thread-0 is running... Thread-0 is running... Thread-0 is running... Interrupt thread:Thread-0 Thread-0 is running... Thread-0 is exiting... Stopping application...