通过标识关闭线程
通过设置一个标识ture,false。
/**
* 通过标识关闭线程
*/
public class ThreadEnd1 {
volatile static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(){
@Override
public void run() {
while (flag) {
System.out.println("=========");
}
}
};
t.start();
Thread.sleep(5);
shutdown();//关闭
}
private static void shutdown() {
flag = false;
}
}
中断标识关闭线程
/**
* 通过判断线程中断标识
*/
public class ThreadEnd2 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(){
@Override
public void run() {
// while (true) {
// try {
// Thread.sleep(1);
// System.out.println("=========");
// } catch (InterruptedException e) {
// e.printStackTrace();
// break;
// }
// }
while (!isInterrupted()){
}
}
};
t.start();
Thread.sleep(100);
t.interrupt();
}
}
暴力结束线程(推荐)
将执行的线程设置为守护线程,通过结束主线程,结束守护线程
以下代码有点难以理解。
/**
* 利用 守护线程特性,将执行的线程设置为守护线程
*
*/
public class ThreadEnd3 {
private Thread excuteThread;
private boolean finished = false;
public void execute(Runnable task) {
excuteThread = new Thread() {
@Override
public void run() {
Thread inner = new Thread(task);
inner.setDaemon(true); //excuteThread线程结束,inner也就随着结束
inner.start();
try {
inner.join();//inner执行完毕才继续执行下面代码
finished = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
excuteThread.start();
}
public void shutdown(long mills) {
long currentTimeMillis = System.currentTimeMillis();
while (!finished) {
if ((System.currentTimeMillis()-currentTimeMillis) >= mills) {
System.out.println("任务超时需要结束");
excuteThread.interrupt();
break;
}
}
finished = false;
}
public static void main(String[] args) {
ThreadEnd3 threadService = new ThreadEnd3();
threadService.execute(()-> {
System.out.println(11);
});
threadService.shutdown(1000);
}
}
当inner一直执行时,inner.join()一直阻塞,这时调用excuteThread.interrupt()时抛出InterruptedException异常,这样excuteThread执行完毕,相应守护线程inner也随着结束。