我们如何在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 送给学长毕业祝福语简短