更新时间:2022-12-14 11:27:23 来源:极悦 浏览1108次
每当我们想通过调用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
以上就是关于“Java结束线程的方法”,如果大家想了解更多相关知识,可以关注一下本站的多线程教程,里面还有更丰富的知识等着大家去学习,希望对大家能够有所帮助哦。
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习