gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:44 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com