更新时间:2021-10-09 11:02:08 来源:极悦 浏览1364次
每当我们想通过调用Java中Thread 类的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.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
以上就是“在Java中关闭线程”的介绍,希望对大家能够有所帮助。大家如果想了解更多相关知识,不妨来关注一下极悦的Java多线程编程,里面的内容详细,通俗易懂,适合没有基础的小伙伴学习。
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习