使用布林值停止 Java 執行緒
可以透過實現 Runnable 介面並重寫 run() 方法來建立執行緒。然後可以建立一個 Thread 物件並呼叫 start() 方法。
可以使用 Java 中的布林值停止執行緒。當布林值 stop 為 false 時,執行緒執行,當布林值 stop 變為 true 時,它停止執行。
演示此內容的程式如下所示
示例
class ThreadDemo extends Thread {
public boolean stop = false;
int i = 1;
public void run() {
while (!stop) {
try {
sleep(10000);
} catch (InterruptedException e) {
}
System.out.println(i);
i++;
}
}
}
public class Demo {
public static void main(String[] args) {
ThreadDemo t = new ThreadDemo();
t.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
t.stop = true;
System.out.println("The thread is stopped");
}
}輸出
1 2 3 4 5 The thread is stopped
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP