我们如何在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 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短