同步与锁定 [英] Synchronization vs Lock

查看:17

问题描述

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.

而使用同步,它非常清晰且不可能出错:

Whereas with synchronized, it's super clear and impossible to get wrong:

synchronized(myObject) {
    doSomethingNifty();
}

也就是说,Lock对于更复杂的事物可能更有用,因为您无法以如此干净的方式获取和释放.老实说,我宁愿首先避免使用裸露的 Lock,而是使用更复杂的并发控制,例如 CyclicBarrierLinkedBlockingQueue,如果它们满足您的需求.

That said, Locks 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 Locks 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.

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆