Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

java - after catching "InterruptedException", why "Thread.currentThread().isInterrupted()"'s value is false?

as the title.

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();
}

after catching "InterruptedException", why "Thread.currentThread().isInterrupted()"'s value is false?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Javadoc for Thread.sleep (called by TimeUnit.sleep):

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

I think the intention of isInterrupted() is to allow you to detect whether a thread has been interrupted before calling something which would throw InterruptedException. If you've caught InterruptedException, it's fair to assume that the thread has been interrupted...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...