假设我有一个方法:
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(()->{
});
}
还有没有回调的其他方法吗?
最佳答案
也许您可以使用 ReentrantLock
而不是 synchronized
关键字(即 more flexible and powerful )。
例子:
ReentrantLock lock = ...;
public void run(){
if (bar) {
lock.lock();
}
try {
// do something
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
关于java - 有条件地定义同步块(synchronized block),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818738/