java 方法互斥_java – 互斥方法

这篇博客探讨了在多线程环境中如何使用低级API来协调方法调用,以防止线程饥饿问题。作者提出了一种使用synchronized关键字的方案,但指出这可能导致线程饥饿,并建议使用AbstractQueuedSynchronizer来更好地解决这个问题。同时,也提到了使用互斥锁的简单替代方案,虽然会导致线程排队,但由于执行速度快,可能是一个可行的选择。
摘要由CSDN通过智能技术生成

我尝试了一些使用更高级别构造的尝试,但没有想到任何事情.我认为这可能是一个下降到低级API的机会:

EDIT: I actually think you’re trying to set up a problem which is inherently tricky (see second to last paragraph) and probably not needed (see last paragraph). But that said, here’s how it could be done, and I’ll leave the color commentary for the end of this answer.

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 code 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 code here

synchronized(this) {

someMethod2Invocations--;

notifyAll();

}

}

上面的一个明显问题是它可以导致thread starvation.例如,someMethod1()正在运行(并阻塞someMethod2()s),就在它即将完成时,另一个线程出现并调用someMethod1().进行得很好,就像它完成另一个线程启动someMethod1(),依此类推.在这种情况下,someMethod2()永远不会有机会运行.这实际上并不是上述代码中的错误;这是您的设计需求的一个问题,一个好的解决方案应该积极解决.我认为公平AbstractQueuedSynchronizer可以做到这一点,尽管这是一个留给读者的练习. ?

最后,我无法抗拒但是插入一个意见:鉴于ConcurrentHashMap操作非常快,你可能最好只是在两个方法中放置一个互斥锁并完成它.所以是的,线程必须排队以调用someMethod1(),但是每个线程都会非常快速地完成它(因此让其他线程继续).这应该不是问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值