java - 使用synchronized时,Java如何确定哪个线程应该继续执行?

标签 java multithreading concurrency synchronization queue

private static void WaitInQueue(Customer c)
{         
    synchronized(mutex){
       //Do some operation here.
    }              

}

我需要让线程在继续之前等待(一次只有一个),但是,synchronized 似乎没有使用 FIFO 来确定接下来应该继续哪个线程。(看起来像 LIFO)这是为什么?

如何确保第一个在同步时等待的线程将是第一个获取锁的线程?

最佳答案

同步块(synchronized block)不保证公平性 - 理论上可以选择任何等待线程来执行。如果您确实想要公平锁(fifo),请改用 java 5+ 中引入的较新的锁定机制。 例如,参见 documentation for ReentrantLock 。 以下是使用公平锁的方法:

private final ReentrantLock lock = new ReentrantLock(true); //fair lock
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }

但请注意,这会导致整体性能下降,因此不建议这样做。 引用自文档”

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting

关于java - 使用synchronized时,Java如何确定哪个线程应该继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20120324/

相关文章:

java - 将gradle项目导入Spring Tool Suite会导致依赖项错误

java - 包 java.nio.file 不存在

android - 使 IntentService 在执行 handler.postDelayed runnable 之前不会休眠

c++ - 协程 TS 2017 的实现示例

c++ - 这会是一个僵局吗?

java - 如何允许在线程中运行的两个对象在 Java 中进行通信?

java - setOnItemClickListener() 不适用于 Fragment 中的 ExpandableHeightGridView

Java GUI 缩放问题

python - 创建一个线程安全的装饰器类

java - ReentrantReadWriteLock返回的锁是否等同于它的读写锁?