我们如何在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 官宣新年祝福语简短