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

查看:203
本文介绍了为什么信号量中的acquire()方法不必同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java进入Semaphores并正在阅读本文 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 < a>:

Yes that's basically it. Semaphores are thread safe as explained in the javadoc:


内存一致性效果:在调用release方法(如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.

<$ c $中对象的大多数操作c> java.util.concurrent 包是线程安全的。更多详细信息在包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.

这篇关于为什么信号量中的acquire()方法不必同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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