我正在学习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/