Java中如何中断同步语句?
我有两个线程想要在同一个对象上同步。如果满足特定条件,则线程 A
需要能够中断线程 B
。这是两个线程做什么/应该做什么的一些伪代码。
A:
public void run()
{
while(true)
{
//Do stuff
synchronized(shared)
{
//Do more stuff
if(condition)
{
B.interrupt();
}
}
}
}
B:
public void run()
{
while(true)
{
try
{
//Do stuff
synchronized(shared)
{
//Do more stuff
}
}
catch(InterruptedException e)
{
continue;
}
}
}
这是我无法解决的情况:
- 线程
A
获取共享资源并执行一些操作。 - 同时,线程
B
到达同步块,并等待A
释放其共享资源。 - 线程
A
在做事情时,意识到线程B不应该拥有共享资源,并尝试中断线程B
。但线程B
已经超出了可能抛出InterruptedException
的范围。
我的问题是,有什么方法可以在线程等待某些内容同步时中断该线程吗?
I have two threads that want to synchonize on the same object. Thead A
needs to be able to interrupt Thread B
if a certain condition has been fullfilled. Here is some pseudo-code of what the two threads do/should do.
A:
public void run()
{
while(true)
{
//Do stuff
synchronized(shared)
{
//Do more stuff
if(condition)
{
B.interrupt();
}
}
}
}
B:
public void run()
{
while(true)
{
try
{
//Do stuff
synchronized(shared)
{
//Do more stuff
}
}
catch(InterruptedException e)
{
continue;
}
}
}
Here's the situation I can't resolve:
- Thread
A
grabs the shared resource and does some stuff. - Meanwhile, Thread
B
reaches the synchronized block, and awaits forA
to release its shared resource. - Thread
A
, while doing stuff, realized that Thread B should not have the shared resource, and tries to interrupt ThreadB
. But ThreadB
has already surpassed the points where anInterruptedException
could be thrown.
My question is, is there any way to interrupt a thread while it is waiting to be synchronized
on something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于这种事情,您应该使用
java.util.concurrent.locks
- 它们具有更多功能,包括可中断锁。编辑:如果您无法使用这些类,请查看 jkff 的答案 - 您的要求可以通过
wait()
/notify()
来满足机制,但很容易引入微妙的错误。For this kind of thing, you should use the classes in
java.util.concurrent.locks
- they have far more capabilities, including interruptable locks.Edit: If you cannot use those classes, then look at jkff's answer - your requirements can be met with the
wait()
/notify()
mechnism, but it's easy to introduce subtle bugs.事实上,您应该使用锁或使用
Object.wait()
、Object.notify()
和Object.notifyAll()
来实现您的东西方法(锁实际上是用它们实现的)。不要忘记处理所谓的“虚假唤醒”(即使没有人调用notify()
或notifyAll()
,wait()
也可能返回>,因此应该始终在循环中调用它来检查您正在等待的条件是否得到满足)。Indeed you should use the locks or implement your stuff with the
Object.wait()
,Object.notify()
andObject.notifyAll()
methods (locks are actually implemented with them). Do not forget to handle the so-called 'spurious wakeups' (wait()
may return even if noone callednotify()
ornotifyAll()
, so it should always be called in a loop that checks that the condition you're waiting for is satisfied).不,但是
ReentrantLock.lockInterruptically()
的行为与原始monitorenter
指令类似,并且可以被中断。No, but
ReentrantLock.lockInterruptibly()
behaves similarly to the primitivemonitorenter
instruction and can be interrupted.