说我有一个方法:
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(()->{
});
}
还有其他方法可以做到吗,没有回调?
而不是synchronized
关键字,也许你可以使用ReentrantLock
(这是more flexible and powerful)。
例:
ReentrantLock lock = ...;
public void run(){
if (bar) {
lock.lock();
}
try {
// do something
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}