使用场景:
在一个线程内去取消另一个线程正在执行的任务。
中断原理:
中断机制是一种协作机制,通过中断并不能直接终止另一个线程,而是需要被中断的线程自己去处理中断。中断不会强求被中断的线程一定要在某个点进行中断处理,中断线程可以自行决定什么时候处理中断请求。
Java中断实现:
java.lang.Thread 类提供了几个方法来操作这个中断状态,这些方法包括:
public static Boolean interrupted()
静态方法,测试当前线程是否已经中断,线程的中断状态由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。
public Boolean isInterrupted()
测试线程是否已经中断。线程的中断状态不受该方法的影响。
public void interrupt()
中断线程。发起中断请求,设置中断标志位。
实例:
public class InterruptTest {
private static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Runnable() {
@Override
public void run() {
while (flag) {
System.out.println("doing job 1 step....");
if (Thread.currentThread().isInterrupted()) {
System.out.println(".........interrupt 1");
}
System.out.println("doing job 2 step....");
if (Thread.currentThread().isInterrupted()) {
System.out.println(".........interrupt 2");
flag = false;
}
System.out.println("doing job 3 step....");
}
}
});
a.start();
Thread.sleep(1000);
a.interrupt();
}
}
程序能正常结束。
public class InterruptTest {
private static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Runnable() {
@Override
public void run() {
while (flag) {
System.out.println("doing job 1 step....");
if (Thread.interrupted()) {
System.out.println(".........interrupt 1");
}
System.out.println("doing job 2 step....");
if (Thread.currentThread().isInterrupted()) {
System.out.println(".........interrupt 2");
flag = false;
}
System.out.println("doing job 3 step....");
}
}
});
a.start();
Thread.sleep(1000);
a.interrupt();
}
}
程序不能正常结束。