更新時(shí)間:2022-12-14 11:27:23 來源:動力節(jié)點(diǎn) 瀏覽1587次
每當(dāng)我們想通過調(diào)用Java 中Thread 類的stop() 方法來停止線程的運(yùn)行狀態(tài)時(shí)。該方法會停止正在運(yùn)行的線程的執(zhí)行,并將其從等待線程池中移除并收集垃圾。當(dāng)線程到達(dá)其方法的末尾時(shí),它也會自動進(jìn)入死狀態(tài)。由于 線程安全問題,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
以上就是關(guān)于“Java結(jié)束線程的方法”,如果大家想了解更多相關(guān)知識,可以關(guān)注一下本站的多線程教程,里面還有更豐富的知識等著大家去學(xué)習(xí),希望對大家能夠有所幫助哦。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743