前言
多线程的结束有很多中方法,一种是自定义标志位实现线程结束、另一种是使用线程自带的标志位来实现、最后一种是采用异常来中断线程;下面我们先来说下inerrupte修改标志位结束线程。
demo
package com.yumingjiang.jvmdemo.thread.end;
/**
* [线程中断--interrupted]
*
* @author : [Administrator]
* @version : [v1.0]
* @createTime : [2023/2/14 0:19]
*/
public class ThreadInterrupteTest {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
//Thread.interrupted()查询线程标志位,默认是false
while (!Thread.interrupted()){
System.out.println("-----------------------");
}
System.out.println("done!");
});
thread.start();
try {
//主线程休眠5s后,修改子线程的标志位,使得子线程结束,15s后主线程结束
Thread.sleep(5000);
thread.interrupt();//修改线程的标志位
Thread.sleep(15000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}