我正在使用
Java进入Semaphores并正在阅读这篇文章
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html.我唯一没有得到的是为什么在同步的上下文中没有使用acquire()方法.看一下上面网站的例子:
他们创建了一个信号量:
private Semaphore semaphore = new Semaphore(100);
并获得这样的许可证:
semaphore.acquire();
现在,两个或多个线程是否有可能同时尝试获取()?如果是这样,计数会有一点问题.
或者,信号量本身是否处理同步?
解决方法
Or,does the semaphore itself handle the synchronization?
是的,基本上就是这样.信号量是线程安全的,如the javadoc中所述:
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的最底部提供.