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() 方法不必同步?
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01