如何在 Java 中停止一個執行緒?
每當我們想透過呼叫 Java 中Thread 類的 stop() 方法來停止一個執行緒的執行狀態時,此方法會停止一個正在執行的執行緒的執行,並將其從等待執行緒池中移除並進行垃圾回收。一個執行緒也會在其方法的末尾時自動進入死狀態。由於執行緒安全問題,在 Java 中stop() 方法已被棄用。
語法
@Deprecated public final void stop()
示例
import static java.lang.Thread.currentThread; public class ThreadStopTest { public static void main(String args[]) throws InterruptedException { UserThread userThread = new UserThread(); Thread thread = new Thread(userThread, "T1"); thread.start(); System.out.println(currentThread().getName() + " is stopping user thread"); userThread.stop(); Thread.sleep(2000); System.out.println(currentThread().getName() + " is finished now"); } } class UserThread implements Runnable { private volatile boolean exit = false; public void run() { while(!exit) { System.out.println("The user thread is running"); } System.out.println("The user thread is now stopped"); } public void stop() { exit = true; } }
輸出
main is stopping user thread The user thread is running The user thread is now stopped main is finished now
廣告