有条件地定义同步块

问题描述 投票:9回答:1

说我有一个方法:

public void run(){
  synchronized(this.foo){

 }
}

但有时当我运行这个方法时,我不需要同步任何东西。

什么是条件同步的好模式?我能想到的唯一模式是回调,类似这样:

public void conditionalSync(Runnable r){
   if(bar){
      r.run();
      return;
   }

  synchronized(this.foo){
     r.run();
  }
}

public void run(){
  this.conditionalSync(()->{


  });
}

还有其他方法可以做到吗,没有回调?

java multithreading concurrency locking synchronized
1个回答
8
投票

而不是synchronized关键字,也许你可以使用ReentrantLock(这是more flexible and powerful)。

例:

ReentrantLock lock = ...;


public void run(){
    if (bar) {
        lock.lock();
    }

    try {
        // do something

    } finally {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.