同步vs锁定 [英] Synchronization vs Lock
问题描述
java.util.concurrent
API提供了一个名为 Lock
的类,它将按顺序序列化控件访问关键资源。它提供诸如 park()
和 unpark()
等方法。
java.util.concurrent
API provides a class called as Lock
, which would basically serialize the control in order to access the critical resource. It gives method such as park()
and unpark()
.
如果我们可以使用 synchronized
关键字并使用 wait
和 notify()notifyAll()
方法。
We can do similar things if we can use synchronized
keyword and using wait()
and notify() notifyAll()
methods.
我想知道其中哪一个在实践中更好,为什么?
I am wondering which one of these is better in practice and why?
推荐答案
如果你只是锁定一个对象,我宁愿使用 synchronized
If you're simply locking an object, I'd prefer to use synchronized
Lock.acquire();
doSomethingNifty(); // Throws a NPE!
Lock.release(); // Oh noes, we never release the lock!
您必须明确执行 try {} finally {}
无处不在。
You have to explicitly do try{} finally{}
everywhere.
而使用synchronized,它是超清晰和不可能出错:
Whereas with synchronized, it's super clear and impossible to get wrong:
synchronized(myObject) {
doSomethingNifty();
}
也就是说, Lock
s可能更有用的更复杂的事情,你不能以这种干净的方式获取和释放。我真的宁愿避免使用裸 Lock
,在第一个地方,只是一个更复杂的并发控制,如 CyclicBarrier
或 LinkedBlockingQueue
,如果他们符合您的需要。
That said, Lock
s may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare Lock
s in the first place, and just go with a more sophisticated concurrency control such as a CyclicBarrier
or a LinkedBlockingQueue
, if they meet your needs.
我从来没有理由使用 wait()
或 notify()
但可能有一些好的。
I've never had a reason to use wait()
or notify()
but there may be some good ones.
这篇关于同步vs锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!