中断在java中主要有3个方法,interrupt(),isInterrupted()和interrupted()。下面分别说明:
- interrupt()方法:
public void interrupt()
中断此线程(此线程是指调用该方法的Thread实例所代表的线程),但实际上只是给该线程设置一个中断标志,并不会实际中断运行中的线程。 - isInterrupted()方法:
public boolean isInterrupted()
测试此线程是否被中断(检查中断标志),但并不清除中断状态。 - interrupted()方法:
public static boolean interrupted()
不管显式调用该方法的线程是哪个,它判断的是当前线程是否已被中断,并清除当前线程的中断状态。
注意:分清“此线程”与“当前线程”!!
下面进行测试说明:
定义一个MyThread类,继承Thread,如下:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("i="+(i+1));
}
}
}
在main方法中测试:
public class Do {
public static void main(String[] args ) {
MyThread thread=new MyThread();
thread.start();
thread.interrupt();
System.out.println("第一次调用thread.isInterrupted():"+thread.isInterrupted());
System.out.println("第二次调用thread.isInterrupted():"+thread.isInterrupted());
//测试interrupted()函数
System.out.println("第一次调用thread.interrupted():"+thread.interrupted());
System.out.println("第二次调用thread.interrupted():"+thread.interrupted());
System.out.println("thread是否存活:"+thread.isAlive());
}
}
输出如下:
注意:尽管interrupted()方法是以thread.interrupted()的形式被调用,但它检测的仍然是main线程而不是检测thread线程,所以thread.interrupted()在这里相当于main.interrupted()。对于这点,下面我们再修改进行测试:
public class Do {
public static void main(String[] args ) throws InterruptedException {
Thread.currentThread().interrupt();
System.out.println("第一次调用Thread.currentThread().interrupt():"
+Thread.currentThread().isInterrupted());
System.out.println("第一次调用thread.interrupted():"
+Thread.currentThread().interrupted());
System.out.println("第二次调用thread.interrupted():"
+Thread.currentThread().interrupted());
}
}
输出如下:
如果想要终止一个线程,在java的api中有stop、suspend等方法,但由于这些方法在使用上存在不安全性,会带来不好的副作用,不建议被使用。实际上,可以通过调用interrupt()方法真正的终止线程,需要在线程的run方法中做一些处理,如直接跳出run()方法使线程结束。比如:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("i="+(i+1));
if(this.isInterrupted()){
System.out.println("通过this.isInterrupted()检测到中断");
System.out.println("第一个interrupted()"+this.interrupted());
System.out.println("第二个interrupted()"+this.interrupted());
break;
}
}
System.out.println("因为检测到中断,所以跳出循环,线程到这里结束,因为后面没有内容了");
}
}
当一个线程处于阻塞状态时,另一线程对该线程调用interrupt方法,它可以迅速中断被阻塞的线程,抛出一个InterruptedException,把线程从阻塞状态中解救出来。测试如下:
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
testThread.interrupt();
System.out.println("main end");
}
@Override
public void run() {
while(!on){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
System.out.println("caught exception right now: "+e);
}
}
}
}
结果如下:
这种情形同样适用io阻塞,通常io阻塞会立即抛出一个SocketException,类似于上面说的InterruptedException。
参考:
Thread类中interrupt()、interrupted()和isInterrupted()方法详解
Java中interrupt的使用