English 中文(简体)
Java:在同步块上等待,谁先去?
原标题:Java: waiting on synchronized block, who goes first?

这个问题的灵感来源于另一个问题

如果多个线程正在等待同步的块,并且锁可用,那么谁先去?是按线程优先级(然后先到先得)吗?

同样的规则是否适用于notify(具有多个等待的线程)?

最佳回答

根据这个家伙的说法:http://tutorials.jenkov.com/java-concurrency/starvation-and-fairness.html

Java对序列没有任何保证。所以我想这不是基于线程优先级

我将尝试进一步了解Java是如何决定谁先去的。

问题回答

还有人提到了公平锁的可用性。如果你真的关心谁先去,那么你可能会遇到实时问题。在这种情况下,您可以使用RTSJ,其中指定了锁获取的排序和其他语义。有关详细信息,请参阅RTSJ规范同步下。引用基本原理部分:

Java s rules for synchronized code provide a means for mutual exclusion but do not prevent unbounded priority inversions and thus are insufficient for real-time applications. This specification strengthens the semantics for synchronized code by mandating priority inversion control, in particular by furnishing classes for priority inheritance and priority ceiling emulation. Priority inheritance is more widely implemented in real-time operating systems and thus is required and is the initial default mechanism in this specification.

第二个问题

其中一个被选择唤醒。这种选择是任意的,由执行人员自行决定。线程通过调用其中一个等待方法来等待对象的监视器。

来自http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#notify()

这取决于线程优先级和线程调度算法,而且对同步块的锁定也不“公平”。这意味着,如果有两个具有相同优先级的等待线程,并且第一个线程等待的时间比第二个线程多,这并不一定意味着第一个线程将首先执行。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签