java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言, 是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台 (即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se)) 的总称
这篇文章主要为大家详细介绍了 Java 中终止线程的三种方法, 具有一定的参考价值, 感兴趣的小伙伴们可以参考一下
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("线程退出!");
- }
- }
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("线程已经退出!");
- }
- }
来源: http://www.phperz.com/article/18/0213/359188.html