有些情况我们需要主动停止正在运行的线程,查阅JDK的文档,发现 interrupt()这个和中断有关的方法。interrupt()方法的功能是中断一个线程的执行。但是,在实际使用当中发现,这个方法不一定能真地中断一个正在运行的线程。
结束一个正在运行的线程
下面通过一个例子来看一看使用interrput()方法中断一个正在运行的线程。
public class InterruptThreadDemo extends Thread{
@Override
public void run() {
while(true){ // 无限循环,并使线程每隔1秒输出一次字符串
System.out.println(Thread.currentThread().getName()+" is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) throws Exception {
InterruptThreadDemo t=new InterruptThreadDemo();
System.out.println("Starting thread...");
t.start(); // 启动线程t
Thread.sleep(2000);
System.out.println("Interrupt thread...");
// /主线程休眠2秒,调用interrupt()方法中断线程t
t.interrupt();
// 主线程休眠3秒,观察中断后的结果
Thread.sleep(3000);
// 主线程结束
System.out.println("Stopping application...");
}
}
运行结果:
Starting thread...
Thread-0 is running
Thread-0 is running
Interrupt thread...
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Stopping application...
Thread-0 is running
Thread-0 is running
Thread-0 is runningThread-0 is running
Thread-0 is running
Thread-0 is running......
从结果可以看出,调用interrput()方法并没有预期的让线程停止。
因为使用Thread.interrupt()只能通知线程中断,而不是强制,具体是否停止还是由被中断的线程本身自己决定。
如何正确停止一个运行中的线程?
可以在代码中加入Thread.currentThread().isInterrupted() 判断检查是否已中断,来配合线程停止。
具体代码如下:
public class InterruptThreadDemo extends Thread{
@Override
public void run() {
while(true){ // 无限循环,并使线程每隔1秒输出一次字符串
if (Thread.currentThread().isInterrupted()){
break;
}else{
System.out.println(Thread.currentThread().getName()+" is running");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws Exception {
InterruptThreadDemo2 t=new InterruptThreadDemo2();
System.out.println("Starting thread...");
t.start(); // 启动线程t
Thread.sleep(2000);
System.out.println("Interrupt thread...");
// /主线程休眠2秒,调用interrupt()方法中断线程t
t.interrupt();
// 主线程休眠3秒,观察中断后的结果
Thread.sleep(3000);
// 主线程结束
System.out.println("Stopping application...");
}
}
运行结果:
Starting thread...
Thread-0 is running
Thread-0 is running
Thread-0 is running
Interrupt thread...
Stopping application...
发现线程被停止了