为什么Thread.interrupt()不能中断试图获取锁的线程 [英] Why can't Thread.interrupt() interrupt a thread trying to acquire lock
本文介绍了为什么Thread.interrupt()不能中断试图获取锁的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Thinking in Java一书中写道, Thread.interrupt()
无法中断试图获取同步锁的线程,我想知道为什么?
In the book Thinking in Java it is written that Thread.interrupt()
cannot interrupt a thread which is trying to acquire a synchronized lock, I want to know why?
推荐答案
只有在声明抛出阻塞操作时才能中断阻塞操作 InterruptedException
。显然, synchronized
块不会声明它,因此在等待获取锁定时无法中断线程。
A blocking operation can be interrupted only if it is declared to throw InterruptedException
. Clearly, a synchronized
block does not declare it, therefore it is impossible to interrupt a thread while it is waiting to acquire a lock.
或者你可以使用显式锁并调用 Lock.lockInterruptibly()
。
Alternatively you can use an explicit lock and call Lock.lockInterruptibly()
.
这篇关于为什么Thread.interrupt()不能中断试图获取锁的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文