?? threadinterrupt.java
字號:
package chapter13;
public class ThreadInterrupt extends Thread {
volatile boolean stop = false; // 共享變量,用于指示線程中斷
public static void main(String args[]) throws Exception {
ThreadInterrupt thread = new ThreadInterrupt();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.stop = true; // 改變共享變量,指示線程中斷
Thread.sleep(3000); // 給一段時間讓線程狀態變為停止
if (thread.isAlive()) { // 測試線程是否處在活動中
System.out.println("The thread is not stopped!");
} else {
System.out.println("The thread is stopped!");
}
}
public void run() {
while (!stop) {
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time < 1000) && (!stop)) {
} // 系統時間,每隔一秒而且沒有被指示中斷則循環一次
}
System.out.println("Thread is exiting under request...");
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -