Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 这些终止线程运行的方法已经被废弃,使用它们是极端不安全的!
1. 线程正常执行完毕,正常结束
也就是让run方法执行完毕,该线程就会正常结束。
但有时候线程是永远无法结束的,比如while(true)。
2. 监视某些条件,结束线程的不间断运行
需要while()循环在某以特定条件下退出,最直接的办法就是设一个boolean标志,并通过设置这个标志来控制循环是否退出。
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit) {
System.out.println("running!");
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(1147); // 主线程延迟5秒
thread.exit = true; // 终止线程thread
thread.join();
System.out.println("线程退出!");
}
}
<br />
3. 使用interrupt方法终止线程
如果线程是阻塞的,则不能使用方法2来终止线程。
public class ThreadInterrupt extends Thread {
public void run() {
try {
sleep(50000); // 延迟50秒
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在50秒之内按任意键中断线程!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("线程已经退出!");
}
}
本文探讨了在Java中安全地终止线程的三种方法:使用boolean标志控制循环、利用interrupt方法中断阻塞线程和避免使用已废弃的Thread类方法。文章提供了具体的代码示例,展示了如何在不同情况下优雅地停止线程。
1502

被折叠的 条评论
为什么被折叠?



