gpt4 book ai didi

java:执行者+任务+锁

转载 作者:搜寻专家 更新时间:2023-10-31 20:15:48 27 4
gpt4 key购买 nike

假设我有一个 ExecutorService(它可以是一个线程池,因此涉及到并发性),它在不同的时间执行一个任务,或者周期性地或者响应一些其他条件。要执行的任务如下:

  • 如果此任务已在进行中,则什么也不做(并让之前运行的任务完成)。
  • 如果此任务尚未在进行中,请运行算法 X,这可能需要很长时间。

我正在想办法实现它。它应该是这样的:

Runnable task = new Runnable() {
final SomeObj inProgress = new SomeObj();
@Override public void run() {
if (inProgress.acquire())
{
try
{
algorithmX();
}
finally
{
inProgress.release();
}
}
}
}

// re-use this task object whenever scheduling the task with the executor

其中 SomeObjReentrantLock (acquire = tryLock() and release = unlock()) 或 AtomicBoolean 或其他东西,但我不确定是哪个。我这里需要 ReentrantLock 吗? (也许我想要一个不可重入锁,以防 algorithmX() 导致此任务递归运行!)或者一个 AtomicBoolean 就足够了吗?


编辑:对于不可重入锁,这合适吗?

Runnable task = new Runnable() {
boolean inProgress = false;
final private Object lock = new Object();
/** try to acquire lock: set inProgress to true,
* return whether it was previously false
*/
private boolean acquire() {
synchronized(this.lock)
{
boolean result = !this.inProgress;
this.inProgress = true;
return result;
}
}
/** release lock */
private void release() {
synchronized(this.lock)
{
this.inProgress = false;
}
}
@Override public void run() {
if (acquire())
{
// nobody else is running! let's do algorithmX()
try
{
algorithmX();
}
finally
{
release();
}
}
/* otherwise, we are already in the process of
* running algorithmX(), in this thread or in another,
* so don't do anything, just return control to the caller.
*/
}
}

最佳答案

你建议的锁实现很薄弱,因为有人很容易不正确地使用它。

下面是一个更有效的实现,具有与您的实现相同的不当使用弱点:

   AtomicBoolean inProgress = new AtomicBoolean(false)
/* Returns true if we acquired the lock */
private boolean acquire() {
return inProgress.compareAndSet(false, true);
}
/** Always release lock without determining if we in fact hold it */
private void release() {
inProgress.set(false);
}

关于java:执行者+任务+锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4876776/

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