interrupt()方法不起作用的原因

2019-01-15  本文已影响19人  野小火

当线程A正在wait或者sleep的时候,其他线程调用线程A的interrupt方法后,线程A会抛出InterruptedException异常信息。

但是如果出现一下代码的时候你会发现不会抛出InterruptedException异常信息

Thread threadA = new Thread() {
    @Override
    public void run() {
        long time = System.currentTimeMillis();
        while (System.currentTimeMillis() - time < 1000) {
            // 执行while的时候不会检查线程中断状态
            // 假如这个期间,我们对当前线程进行了interrupt操作
        }
        // 如果这里先将线程睡眠或者wait,
        try {
            // sleep或者wait的时候会检查线程中断状态
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // 因为while期间的intterrupt,抛出了异常。
        }
        // 这里如果再调用isIntterrupted()方法的时候,你会发现线程不处于中断状态了。
        try {
            System.out.println("线程开始等待");
            synchronized (this) {
                // 当再次进行wait的时候,你会发现不会再抛出异常了
                wait(); 
            }
            System.out.println("等待结束");
        } catch (InterruptedException e) {
            System.err.println("wait InterruptedException");
        }
    }
};
上一篇下一篇

猜你喜欢

热点阅读