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().

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?

推荐答案

If you're simply locking an object, I'd prefer to use synchronized

Example:

Lock.acquire();
doSomethingNifty(); // Throws a NPE!
Lock.release(); // Oh noes, we never release the lock!

You have to explicitly do try{} finally{} everywhere.

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

synchronized(myObject) {
    doSomethingNifty();
}

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.

I've never had a reason to use wait() or notify() but there may be some good ones.

Java相关问答推荐

将linkedHashMap扩展到Java中的POJO类

Java自定义ThreadPool—暂停任务提交并取消当前排队任务

如何在返回bigint []值的子查询中使用any?

流迭代列表<;对象>;上的NoSuchElementException

如何以干净的方式访问深度嵌套的对象S属性?

如何使用值中包含与号的查询参数创建一个java.net.URI

Bean定义不是从Spring ApplationConext.xml文件加载的

try 从REST API返回对象列表时出错

Dijkstra搜索算法的实现

在应用getCellFormula()时,Excel引用中的文件名始终为";[1]";使用Apache POI()

不能在 map 上移除折线

活泼的一次判断成语,结果中等

JavaFX:为什么我的ComboBox添加了一个不必要的单元格的一部分?

OAuth:登录后无法查看Google邮箱地址

将基于实例编号的对象列表拆分为新的对象列表

如何用Micrometer&;斯普肯

@此处不能应用可为null的批注

在JPanel上使用GridBagLayout并将JButton放在里面时出现问题

OpenAPI Maven插件生成错误的Java接口名称

从 Java 17 切换回 Java 8 后出现的问题