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() 方法不必同步?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
