何时设置线程的中断标志?

时间:2015-05-29 09:30:29

标签: java multithreading

我有以下一段对我来说很奇怪的代码。日志消息显示当前线程没有被中断,为什么会这样?

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

1 个答案:

答案 0 :(得分:4)

当有人在线程上调用.interrupt()时设置它。

你没有在你的情况下看到中断状态的原因是.take()将在抛出异常时清除该标志。

试试这个,看看:

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

通常,.interrupt()不会以任何方式强制(除非线程正在等待,请参阅下面的Javadoc以获取详细信息) - 由线程进行轮询以进行轮询并相应地执行操作。 (就像在这种情况下,清除标志并抛出InterruptedException。)

您可以在此处详细了解.interrupt()的工作原理:https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--