在Java中,可以通过Thread对象的interrupt()方法来中断对象引用的线程,通过Thread类的静态方法interrupted()测试当前线程的中断状态,通过Thread对象的isInterrupted()方法测试对象引用的线程的中断状态。
如果线程被阻塞在Object类的wait(), wait(long), 或者 wait(long, int) 方法,或者被阻塞在Thread类的join(), join(long), join(long, int), sleep(long), 或者sleep(long, int)方法,那么中断本线程后,本线程的中断状态被清除,并且本线程将收到一个InterruptedException异常。
代码示例:
package com.thb;
public class Test2 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("<在another线程中探测> 刚进来," + Thread.currentThread().getName() + " interrupted :" + Thread.currentThread().isInterrupted());
// 睡眠5秒钟
Thread.sleep(5000);
} catch (InterruptedException e) {
// 中断状态被清除
System.out.println("<在another线程中探测> 捕获InterruptedException后," + Thread.currentThread().getName() + "interrupted :" + Thread.currentThread().isInterrupted());
}
}
}, "another");
t.start();
// 此时线程another的中断状态应该是false
System.out.println("<在主线程中探测>中断another线程前," + t.getName() + " interrupted: " + t.isInterrupted());
// 主动中断线程another
t.interrupt();
System.out.println("<在主线程中探测>中断another线程后," + t.getName() + " interrupted: " + t.isInterrupted());
}
}
一次运行输出的结果: