【问题标题】:after catching "InterruptedException", why "Thread.currentThread().isInterrupted()"'s value is false?捕获“InterruptedException”后,为什么“Thread.currentThread().isInterrupted()”的值为假?
【发布时间】:2012-03-28 05:31:51
【问题描述】:

作为标题。

public static void main(String[] args) throws InterruptedException {

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().isInterrupted());   //print false, who reset the interrupt?

            }
        }
    });

    thread.start();
    TimeUnit.SECONDS.sleep(1);
    thread.interrupt();
}

捕获“InterruptedException”后,为什么“Thread.currentThread().isInterrupted()”的值为false?

【问题讨论】:

    标签: java multithreading interrupt


    【解决方案1】:

    来自Thread.sleep(由TimeUnit.sleep 调用)的Javadoc:

    InterruptedException - 如果任何线程中断了当前线程。抛出该异常时清除当前线程的中断状态。

    我认为isInterrupted() 的目的是让您检测线程是否在调用会抛出InterruptedException 的东西之前被中断。如果您捕获 InterruptedException,则可以假设线程被中断...

    【讨论】:

    • +1:如果你的线程再次被中断,在抛出异常之后但在你检查它之前,它将是true
    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多