我们如何在Java中停止线程?
每当我们想通过调用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
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短