Thread之interrupt()函数解析

函数interrupt()对处于RUNNABLE或WAITING(包括TIME_WAITING)状态的线程进行中断,作用如下:

RUNNABLE线程

例如:

package interrupt;

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 50000; i++) {
            System.out.println("i = " + (i + 1));
        }
    }
}

上述代码产生的线程,运行后状态为RUNNABLE。对其使用interrupte()函数,再使用函数isInterrupted()进行判断,结果为true,确认中断标志位被标识。原因是线程没有被真正终止,中断后for循环语句将继续执行。

WAITING(包括TIME_WAITING)线程

例如:

package interrupt;

public class MyThread extends Thread {
    @Override
    public void run() {
        try {
            for (int i = 0; i < 50000; i++) {
                System.out.println("i = " + (i + 1));
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

上述代码产生的线程,运行后状态为TIME_WAITING。对其使用interrupte()函数,再使用函数isInterrupted()进行判断,结果为false,确认中断标志位被清除。原因是此时线程被中止状态为TERMINATED,中断标志位复位。中断后抛出InterrupedException,for循环语句不再执行。

Thread.interrupted()函数

该函数为类函数,在使用interrupt()函数后,使用interrupted()对当前线程是否中断进行判断,并清除中断标志位。如果重复调用,第二次调用会返回false,因为第一次已经清除了中断标志位。

猜你喜欢

转载自blog.csdn.net/xiewz1112/article/details/82349132