Why does the acquire() method in Semaphores not have to be synchronized?(为什么 Semaphores 中的 acquire() 方法不必同步?)
问题描述
我正在学习 Java 中的信号量,并且正在阅读这篇文章 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html .我唯一不明白的是为什么在同步上下文中不使用 acquire() 方法.查看上面网站的示例:
I am getting into Semaphores in Java and was reading this article http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html . The only thing I don't get is why the acquire() method is not used in a synchronized context. Looking at the example from the above webiste:
他们创建一个信号量:
private Semaphore semaphore = new Semaphore(100);
并像这样获得许可:
semaphore.acquire();
现在,两个或多个线程是否可能同时尝试获取()?如果是这样,计数会有一点问题.
Now, wouldn't it be possible that two or more threads try to acquire() at the same time? If so, there would be a little problem with the count.
或者,信号量本身是否处理同步?
Or, does the semaphore itself handle the synchronization?
推荐答案
或者,信号量本身是否处理同步?
Or, does the semaphore itself handle the synchronization?
是的,基本上就是这样.信号量是线程安全的,如 javadoc一个>:
Yes that's basically it. Semaphores are thread safe as explained in the javadoc:
内存一致性效果:在调用释放"方法(如 release())之前线程中的操作发生在另一个线程中成功的获取"方法(如 acquire())之后的操作.
Memory consistency effects: Actions in a thread prior to calling a "release" method such as release() happen-before actions following a successful "acquire" method such as acquire() in another thread.
java.util.concurrent
包中对象的大多数操作都是线程安全的.package javadoc.
Most operations on the objects in the java.util.concurrent
package are thread safe. More details are provided at the very bottom of the package javadoc.
这篇关于为什么 Semaphores 中的 acquire() 方法不必同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Semaphores 中的 acquire() 方法不必同步?


- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01