互斥方法

互斥方法,第1张

互斥方法

尝试了几次使用更高级别的构造的尝试,但没有想到。我认为这可能是一个下降到低级API的机会:

编辑:
我实际上认为您正在尝试设置一个固有的棘手问题(请参阅第二至第二段),并且可能不需要(请参阅最后一段)。但这就是说,这是可以完成的方法,我将在此答案的结尾处留下颜色评论。

private int someMethod1Invocations = 0;private int someMethod2Invocations = 0;public void someMethod1() {    synchronized(this) {        // Wait for there to be no someMethod2 invocations -- but        // don't wait on any someMethod1 invocations.        // once all someMethod2s are done, increment someMethod1Invocations        // to signify that we're running, and proceed        while (someMethod2Invocations > 0) wait();        someMethod1Invocations++;    }    // your pre here    synchronized (this) {        // We're done with this method, so decrement someMethod1Invocations        // and wake up any threads that were waiting for that to hit 0.        someMethod1Invocations--;        notifyAll();    }}public void someMethod2() {    // comments are all ditto the above    synchronized(this) {        while (someMethod1Invocations > 0) wait();        someMethod2Invocations++;    }    // your pre here    synchronized(this) {        someMethod2Invocations--;        notifyAll();    }}

上面的一个明显问题是它可能导致线程饥饿。例如,

someMethod1()
正在运行(并阻塞
someMethod2()
),并且在即将完成时,另一个线程随之出现并调用
someMethod1()
。这样就可以进行了,就在结束时
另一个
线程开始了
someMethod1()
,依此类推。在这种情况下,
someMethod2()
将永远没有机会运行。实际上,这并不是上面代码中的直接错误。这是您非常需要设计的问题,一个好的解决方案应该积极地解决这个问题。我认为一个公平的AbstractQueuedSynchronizer可以解决问题,尽管这是留给读者的练习。:)

最后,我

ConcurrentHashMap
忍不住要发表意见:鉴于 *** 作相当快,因此最好在这两种方法之间放一个互斥体,然后用它完成。因此,是的,线程将不得不排队等待调用
someMethod1()
,但是每个线程将非常快速地完成其轮换(并让其他线程继续进行)。这不应该是一个问题。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5586589.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存