关于Java Thread类中的这三个方法,看起来很像,但只有interrupt是打断线程,interrupted和isInterrupted返回的是boolean值。
1、interrupt:对应线程调用此方法时,会标记此线程被打断。
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
2、interrupted:判断当前正在执行的线程是否被打断,并清空打断标记。这里的当前正在执行是指在本线程运行时的线程,而不是哪个线程调用此方法的线程。比如有线程A和线程B,即使在线程B中调用的是a.interrupted()方法,返回的还是判断线程B是否被打断。
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
3、 isInterrupted:判断调用此方法的线程是否被打断,不清空打断标记。但是如果被打断线程继续执行,则再次调用返回false。
public boolean isInterrupted() {
return isInterrupted(false);
}
示例代码:
public class Test {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(1111); // 3
if(Thread.currentThread().isInterrupted()){
System.out.println("t1 interrupt");
System.out.println(Thread.currentThread().isInterrupted());
break;
}
}
}
});
t1.start();
//此处睡一下是为了让t1线程启动
Thread.sleep(200);
t1.interrupt();
System.out.println(t1.isInterrupted());// 1
System.out.println(t1.isInterrupted());// 2
System.out.println(t1.isInterrupted());// 4
System.out.println(t1.isInterrupted());// 5
System.out.println("---------------------");
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted()); // 7
System.out.println(Thread.interrupted()); // 8
}
}
图中注释标数字的需要打断点,并且按照标号顺序执行。
运行主线程,因为执行了t1.interrupt,所以断点1处打印true。
再往下,断点2处也是true。说明isInterrupted方法不会重置标记。
这时我们切换到t1线程,执行一行,断点3处。
再切回主线程继续执行断点4处。
可以看到,只要被打断的线程执行一行,我们再次调用判断是否被打断时,就返回false了。再继续执行断点5依然是false。
我们继续切换到t1线程
可以看到虽然主线程判断是否被打断已经显示false了,但是在自己线程中执行,还是会为true,进入方法并打印语句。
继续回到主线程执行Thread.currentThread().interrupt()方法,执行当前主线程打断。我把代码拿下来
System.out.println("---------------------");
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted()); // 7
System.out.println(Thread.interrupted()); // 8
这时我们断点7执行的是interrupted方法。
interrupted方法,第一次调用之后会情况打断标记。所以断点7打印当前主线程被打断为true,断点8为false。
该方法不论哪个线程谁调用也只是判断正在执行的线程是否被打断。我们可以把代码改为t1.interrupted。
可以看到结果是一样得。