java:executors任务锁

前端之家收集整理的这篇文章主要介绍了java:executors任务锁前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

假设我有一个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

SomeObj是ReentrantLock(acquire = tryLock()和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);
   }
原文链接:https://www.f2er.com/java/437784.html

猜你在找的Java相关文章