同步块 - Java
我意识到Java中提供的同步块基本上是可重入互斥体的实现。然而同步块是原子的吗?
那么如何处理当前在同步块中执行的线程的中断 - 它是否只是通过恢复到目前为止所做的所有更改来释放锁?
编辑:关于问题的中断部分 - Java 中通常如何处理它。例如,我看到许多 Java 代码示例,其中开发人员在线程位于等待队列中时捕获中断。然而,在 catch 块中,它们所做的只是打印已引发中断。我更好奇该线程实际上发生了什么?是否从等待队列中删除?
I realize that the synchronized block provided in Java is basically an implementation of a re-entrant mutex. However is the synchronized block atomic?
So how are interrupts handled for threads currently executing within the synchronized block - does it simply release the lock by reverting all the changes made so far?
EDIT: With regards to the Interrupts part of the question - how is it generally handled in Java. For instance, I see many java code examples wherein developers catch an interrupt when (say) a thread is in the wait queue. However within the catch block all they do is print that an interrupt has been raised. I am more curious as to what actually happens to that thread? Is it removed from the wait queue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
-- 原子性
同步块有助于实现原子性 - 但它们的数据操作不能保证是原子性的。为了使同步块中的内容原子化,您经常使用原子数据结构,例如 getter 和 setter,例如 AtomicBoolean。
最新的 java 版本支持大量很棒的原子类,例如原子 int 数组。
-- 如何处理中断:
同步不会显式处理中断 - 同步块仅保证在执行时该块不能被另一个线程重新进入。
-- atomicity
Synchronized blocks help to implement atomicity - but their data operations can't be garaunteed to be atomic. To make the stuff in a synchronized block atomic, you use often use atomic data structures like getters and setters, for example, AtomicBoolean.
There are a cornucopia of great atomic classes, like atomic int arrays, supported by the latest java version.
-- how interrupts are handled :
Interrupts are not explicitly handled by synchronization - synchronous blocks only gaurantee that, while executing, the block cannot be reentered by another thread.
是的,同步块强制该块和在同一对象上同步的任何块都是原子的。
中断与Java中的同步完全不同。每个线程都有一个
每当您调用
interrupt()
在线程上。如果设置了中断标志并停止休眠,诸如 Thread.sleep() 之类的方法将抛出 InterruptedException。请注意,
Thread.sleep()
在睡眠期间不会放弃任何锁定。仅当执行流出该块时,与同步块关联的锁才会被释放。Yes, a synchronized block enforces that this block and any block that is synchronized on the same Object are atomic.
Interrupts are completely different to synchronization in Java. Each Thread has an
interruptedStatus
flag that is set whenever you callinterrupt()
on the Thread. Methods such asThread.sleep()
throw an InterruptedException if the interrupt flag is set and halt their sleeping.Note that
Thread.sleep()
does not relinquish any locks during the sleep period. The lock associated with a synchronized block is only released when the execution flows out of the block.您不必处理锁。正如JLS 14.18中所写的< strong>同步语句:
You do not have to handle the lock. As written in the JLS 14.18 The synchronized Statement: