- 使用标志位退出线程
- 使用stop方法强制终止线程
- 使用interrupt终止线程
1. 使用标志位退出线程
这种也是最常用的方法,就是定义一个boolean型的标志位,在线程的run方法中根据这个标志位是true还是false来判断是否退出,这种情况一般是将任务放在run方法中的一个while循环中执行的。
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit) {
//do something
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(5000); // 主线程延迟5秒
thread.exit = true; // 终止线程thread
thread.join();
System.out.println("线程退出!");
}
}
或者,run方法中如果你不是使用while循环处理,则可以隔一段代码调用一次标志位判断:
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void run() {
//do something
if (!exit)return;
//do something
if (!exit)return;
//do something
if (!exit)return;
//do something
if (!exit)return;
}
}
2. 使用stop方法强制终止线程
使用stop方法可以强行终止正在运行或挂起的线程。我们可以使用如下的代码来终止线程:
thread.stop();
虽然这样可以终止线程,但使用stop方法是很危险的,就象突然关闭计算机电源,而不是按正常程序关机一样,可能会产生不可预料的结果,因此,并不推荐使用stop方法来终止线程。
3. 使用interrupt终止线程
使用interrupt方法来终端线程可分为两种情况:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isInterrupted()){……}
来判断线程是否被中断。
在第一种情况下使用interrupt方法,sleep方法将抛出一个InterruptedException例外,而在第二种情况下线程将直接退出。
第一种情况示例代码:
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("线程已经退出!");
}
}
运行结果:
在50秒之内按任意键中断线程!
sleep interrupted
线程已经退出!
在调用interrupt方法后, sleep方法抛出异常,然后输出错误信息:sleep interrupted.
第二种情况示例代码:
public class ThreadInterrupt extends Thread {
public void run() {
while (!isInterrupted()) {
//do something
}
}
public static void main(String[] args) throws Exception {
Thread thread = new ThreadInterrupt();
thread.start();
thread.interrupt();
thread.join();
System.out.println("线程已经退出!");
}
}
注意:在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法interrupted()
,一个是非静态的方法isInterrupted()
,这两个方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted
可以用来判断其他线程是否被中断。因此,while (!isInterrupted())
也可以换成while (!Thread.interrupted())
。
参考链接:https://www.cnblogs.com/HDK2016/p/6854683.html