线程除了正常的结束外,还有哪些方式可以终止?
通过设置退出标识终止线程
/**
* @description: 设置退出标识使线程终止
* @author: Cyril
* @create: 2019/11/18
*/
public class ThreadExitFlagDemo extends Thread {
/**
* 退出标识
* volatile 内存可见性
*/
public volatile boolean exit = false;
@Override
public void run() {
while (!exit) {
}
System.out.println("线程ThreadExitFlagDemo退出!");
}
public static void main(String[] args) throws InterruptedException {
ThreadExitFlagDemo threadExitFlagDemo = new ThreadExitFlagDemo();
threadExitFlagDemo.start();
//主线程休眠3秒钟
sleep(3000);
//设置退出标识
threadExitFlagDemo.exit = true;
//主线程让出资源,让threadExitFlagDemo线程继续执行,直到退出
threadExitFlagDemo.join();
System.out.println("主线程退出");
}
}
通过设置中断标识终止线程
/**
* @description: 通过interrupt()方法使线程终止
* @author: Cyril
* @create: 2019/11/19
*/
public class ThreadExitInterruptDemo extends Thread {
/**
* 退出标识
*/
volatile boolean exit = false;
@Override
public void run() {
while (!exit) {
System.out.println(getName() + " is running");
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
System.out.println("week up from block...");
exit = true;
}
}
System.out.println(getName() + " is exiting...");
}
public static void main(String[] args) throws InterruptedException {
InterruptThread interruptThread = new InterruptThread();
System.out.println("Starting thread...");
interruptThread.start();
Thread.sleep(3000);
System.out.println("Interrupt thread...: " + interruptThread.getName());
// 设置退出标识为true,当线程阻塞时,使线程处于处于不可运行状态时,但该线程此时根本无法检查循环标志,当然也就无法立即中断
// interruptThread.exit = true;
// 阻塞时退出阻塞状态
interruptThread.interrupt();
// 主线程休眠3秒以便观察线程interruptThread的中断情况
Thread.sleep(3000);
System.out.println("Stopping application...");
}
}