简体   繁体   中英

When is thread's interrupt flag set?

I have the following piece of code which is weird to me. The log message shows that the current thread is not interrupted, why's that ?

final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
Thread thread = new Thread() {
  public void run() {

    while (!Thread.currentThread().isInterrupted()) {
      try {
        LOG.info("start to take");
        String next = queue.take();
        LOG.info(next);
      } catch (InterruptedException e) {
        LOG.info(e + "");
        LOG.info("IsInterupted:"
            + Thread.currentThread().isInterrupted());
        continue;
      }

    }
  }
};

thread.start();
Thread.sleep(1000);
thread.interrupt();

It is set when someone calls .interrupt() on the thread.

The reason why you are not seeing the interrupted state in your case is that .take() will clear the flag as it throws the exception.

Try this and see:

Thread t = new Thread(() -> {
    while (true)
        System.out.println(Thread.currentThread().isInterrupted());
});
t.start();
Thread.sleep(1000);
t.interrupt();

In general, the .interrupt() is not forced in any way (unless the thread is waiting, see the Javadoc below for details) - it is up to the thread to poll for it and act accordingly. (Like in this case, clear the flag and throw an InterruptedException.)

You can read more of how .interrupt() works here: https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM