一. 如何终止线程
-
线程run运行完毕,线程自动终止
-
在while循环条件中设置 标志位
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void exit(){
this.exit = true;
}
public void run(){
while (!exit);
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(3000); // 主线程延迟3秒
thread.exit(); // 终止线程thread
thread.join();
System.out.println("线程退出!");
}
}
- 使用interrupt()方法(推荐)
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void exit(){
this.exit = true;
}
public void run(){
while (!Thread.currentThread.isInterrupted()){
try {
System.out.println("线程开始。");
Thread.sleep(200000);
System.out.println("线程结束。");
} catch (InterruptedException e) {
System.out.println("遇到sleep,进入catch异常");
e.printStackTrace();
// 方法1.阻塞时退出方法
// break;
//方法2. 或者重新标记线程状态为中断,因为catch 打印异常会将中断设置为默认的false
Thread.currentThread.interrupt();
}
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(3000); // 主线程延迟3秒
thread.interrupt(); // 终止线程thread
thread.join();
System.out.println("线程退出!");
}
}
二. JVM关闭的几种情况
说明:JAVA线程不独立进程,因此JVM退出时,所有的线程都会关闭,程序宕机时也是如此。
正常关闭
1. 所有非daemon线程退出
2. 调用System.exit()
(IDEA点击终止程序按钮也属于这种情况)
4. SIGINT(ctrl+c)
5. SIGTERM(kill -15)
异常关闭
1. 未捕获的异常
2. oom
强制关闭
1. SIGKILL(kill -9)
2. 应用crash
3. 机器宕机
补充:守护线程与非守护线程
守护线程设置要在线程启动前
thread.setDaemon(true);
thread.start();