问题描述
我有这种方法:
public void lock(Asyncc.IAsyncCallback<Unlock, Object> cb) {
synchronized (this) {
if (this.locked) {
this.queue.add(cb);
return;
}
this.locked = true;
}
cb.done(null, this.makeUnlock(true));
}
有什么技巧可以用来避免sync()调用吗?
我认为分配布尔值是原子的,因此一次只能有一个线程可以做到这一点。
这个想法是我们要避免2个线程获得该锁。 我们也不希望两个不同的代码路径获取锁,即使它们在同一线程中也是如此。
1楼
一种可能加快其加速速率的方法是执行以下操作:
public void lock(Asyncc.IAsyncCallback<Unlock, Object> cb) {
boolean add = false;
synchronized (this) {
if (this.locked) {
add = true;
}
else {
this.locked = true;
}
}
if(add){
this.queue.add(cb);
return;
}
cb.done(null, this.makeUnlock(true));
}
但我仍然不知道是否有办法避免同步块。
2楼
也许可以通过使用而不是boolean来避免同步块