
每当我们想要通过调用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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号