public class StopThread { // 靜態欄位的讀寫不必須要同步才能生效,儘管讀寫是原子的(atom) private static boolean stopRequested; /** * 對靜態共享欄位的寫進行同步 */ private static synchronized void requestStop() { stopRequested = true; System.out.println("stopRequested"); } /** * 對靜態共享欄位的讀進行同步 * @return boolean */ private static synchronized boolean stopRequested() { return stopRequested; } public static void main(String[] args) throws InterruptedException { Thread bkThread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (!stopRequested()) { System.out.println(i); i++; } } }); // 啟動非同步執行緒 bkThread.start(); // 主執行緒休眠1秒 TimeUnit.SECONDS.sleep(1); // 發出stop指令(stopRequested = true) requestStop(); } }