加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java:executors任务锁

发布时间:2020-12-14 19:13:32 所属栏目:Java 来源:网络整理
导读:假设我有一个ExecutorService(可以是一个线程池,因此涉及并发),它可以在不同的时间执行任务,定期或响应某些其他条件.要执行的任务如下: 如果此任务已在进行中,则不执行任何操作(并让以前运行的任务完成). 如果此任务尚未进行,请运行算法X,这可能需要很长时

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读