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() 方法不必同步?


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01