为什么 Semaphores 中的 acquire() 方法不必同步? [英] Why does the acquire() method in Semaphores not have to be synchronized?

查看:22
本文介绍了为什么 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() 方法不必同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆