使用线程同时访问Java同步块?
两个线程如何同时访问同步块?也就是说,如何让一个线程为另一个线程提供执行同步块的机会,甚至在该线程完成同一同步块的执行之前?
How can two threads access a synchronized block simultaneously? That is, how can I make one thread give the chance for the other thread to execute a synchronized block, even before this thread finishes the execution of the same synchronized block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请参阅 wait(), notify() 和 notifyAll()。
编辑:对您问题的编辑不正确。 sleep() 方法不释放监视器。
例如:
See wait(), notify(), and notifyAll().
Edit: The edit to your question is incorrect. The sleep() method does not release the monitor.
For example:
听起来您可能需要考虑使用多个同步块,特别是如果一个线程正在执行阻塞操作,从而阻塞另一个想要执行块中其他操作的线程。
It sounds like you might want to consider using more than one synchronized block, particularly if there's a blocking operation that one thread is getting caught on and thus blocking another thread that wants to execute something else in the block.
同步块是(根据定义)一次只能由一个线程访问的代码块。
如果您希望另一个线程进入此块,而另一个线程当前也在处理它,则确实会使同步块方案毫无用处。
您可能想将同步块拆分为许多其他块。
A synchronized block is a block of code which can (by definition) only be accessed by one thread at a time.
Saying that you want another thread to enter this block while another thread also currently processes it, does make the synchronized block scheme useless.
You probably want to split the synchronized block into many other ones.
我可以查看是否有一个线程在监视器对象上调用
wait()
的唯一方法。然后它将释放监视器并等待通知,而其他线程可以执行同步块。然后其他线程必须调用notify()/notifyAll(),以便第一个线程取回监视器并继续。The only way I can see if one thread calls
wait()
on monitor object. Then it will release monitor and wait for notification while other thread can execute synchronized block. Then other thread will have to callnotify()/notifyAll()
so first thread gets monitor back and continue.线程可以使用lock.wait() 释放其监视器。然后另一个线程可以拿起监视器并进入同步块。
示例:
这会打印:
但是,允许互斥块以非原子方式运行并不是“黑客”。如果您要使用像这样的非常低级的同步原语,您需要知道您在做什么。
A thread can release its monitor using
lock.wait()
. Another thread can then pick up the monitor and enter the synchronized block.Example:
This prints:
However it's not a "hack" to allow a mutually exclusive block to be run non-atomically. If you're going to use very low-level synchronization primitives like this you need to know what you're doing.