java - 当当前线程已经运行时,为什么要中断它呢?

标签 java multithreading synchronization

我正在学习java中的锁定机制,并发现了LockSupport类中作为示例给出的一些代码,其中线程通过调用interrupt()方法来中断自身。我很困惑,当一个线程已经在运行时,为什么它会中断自己。

我还想向大家澄清,我知道当 current thread is interrupted inside the catch block 时会发生什么。但我想知道运行线程中断本身时会发生什么。

代码来自LockSupport

示例代码在这里

class FIFOMutex {
    private final AtomicBoolean locked  = new AtomicBoolean(false);
    private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();

    public void lock() {
        boolean wasInterrupted = false;
        Thread current = Thread.currentThread();
        waiters.add(current);

        // Block while not first in queue or cannot acquire lock
        while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
            LockSupport.park(this);
            if (Thread.interrupted()) // ignore interrupts while waiting
                wasInterrupted = true;
        }
        waiters.remove();
        if (wasInterrupted)          // reassert interrupt status on exit
            current.interrupt();    // Here it is interrupting the currentThread which 
    }

    public void unlock() {
        locked.set(false);
        LockSupport.unpark(waiters.peek());
    }
}

最佳答案

I want to know what happen when running Thread interrupt itself.

中断标志被设置为真,没有别的。没有什么比触发异常或向线程发出信号更神奇的了。

如果您中断另一个被可中断方法阻塞的线程,这将触发该方法抛出 InterruptedException。

当你打电话时

Thread.interrupted()

这会清除该标志,如果您想再次设置它,则需要使用 interrupt() 将标志设置为 true 以便其他代码可以检测到该线程被打断了。

一个更简单的解决方案是使用 Thread.currentThread().isInterrupted() ,它不会清除标志。

关于java - 当当前线程已经运行时,为什么要中断它呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23633490/

相关文章:

java - 如何将文件保存在内存中并读取文件输出流?

java - Maven deps 在 POM 中找不到版本字段

java - 已显示合并条款

java - Android 中的线程安全数据管理以保持 UI 线程自由

java - 同步块(synchronized block)不会锁定

java - Eclipse IDE 无法与 Google 备份和同步一起使用

java - 如何使用jsp :include param tag into another jsp传递对象

multithreading - 为什么 xsub 中的静态变量不是线程安全的?

c# - WCF 是否使用 ThreadPool 为 PerCall 服务创建新实例?

networking - Web 浏览器作为 Web 服务器