每當我們想要透過呼叫Java中Thread類別的stop()方法來停止一個正在執行的執行緒時,該方法會停止正在運行的線程的執行,並將其從等待線程池中移除並進行垃圾回收。當執行緒達到其方法的末尾時,它也會自動轉移到死亡狀態。由於線程安全性問題,stop()方法在Java中已被棄用。
@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.<strong>stop()</strong>; 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
以上是我們如何在Java中停止一個執行緒?的詳細內容。更多資訊請關注PHP中文網其他相關文章!