版权声明:本文为博主原创文章,允许转载,请标明出处。
中断线程, 具体使用场景可以查看下面的源码以及注释
/**
* 中断线程
*
* 除非当前线程中断自身,
* 否则在checkAccess中将会抛出SecurityException
*
* 如果当前线程在 wait、join、sleep 中被阻塞,
* 将会清除它的中断状态(isInterrupted() is false),
* 并抛出InterruptedException
*
* 如果当前线程在java.nio.channels上的I/O操作被阻塞,
* 则通道将被关闭,线程的中断状态被设置(isInterrupted() is true),
* 并抛出ClosedByInterruptException
*
* 如果当前线程在java.nio.channels.Selector中被阻塞,
* 则线程的中断状态被设置(isInterrupted() is true),
* 并立即返回,可能带有非零值。
* 类似于调用了java.nio.channels.Selector的wakeup方法
*
* 如果上面的条件都不存在,
* 则线程的中断状态被设置(isInterrupted() is true)
*
*/
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();
}
/**
* 测试这个线程是否被中断,
* 但是线程的中断状态,不受此方法的影响
*
* 当一个线程死亡的时候,
* 设置线程的中断状态将会被忽略,
* 调用此方法将返回false
*
* 如果这个线程被中断(即:中断状态被设置)
* 则返回true,否则,返回false。
*/
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
* 测试当前线程是否中断
* 返回结果与isInterrupted返回值一样,
*
* 但该方法会清除线程的中断状态
*
* 即:不过当前线程状态如何,如果连续调用两次此方法,
* 则,第二次调用将返回false。
* 因为,第一次调用时已清除了中断状态。
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
package cn.qbz.thread;
import org.springframework.validation.annotation.Validated;
/**
* @Author: 花生米
* @Date: 2018/11/16 10:20
*/
public class InterruptTest {
public static void main(String[] args) throws InterruptedException {
Test2 test2 = new Test2();
System.out.println("\n线程未启动之前:" + test2.isInterrupted());
test2.start();
System.out.println("\n调用interrupt前:" + test2.isInterrupted());
test2.interrupt();
System.out.println("\n调用interrupt,中断状态被设置:" + test2.isInterrupted());
while (true) {
if (test2.isAlive()) {
Thread.sleep(2000);
} else {
break;
}
}
System.out.println("\n线程已死亡:" + test2.isInterrupted());
}
}
class Test2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 600001; i++) {
System.out.print("");
if (i == 600000) {
System.out.println("interrupted:" + Thread.interrupted());
System.out.println("interrupted late::" + isInterrupted());
}
}
System.out.println("线程即将死亡...");
interrupt();
System.out.println("interrupted late::" + isInterrupted());
}
}
interrupted 测试的时当前线程; isInterrupted 测试的时被调用的线程。