默认情况下,Java信号量使用忙等待或等待/通知



问题来了。我在Windows 7上使用JDK 6.0,并尝试使用信号量作为解决同步问题的机制。它工作得很好,但我想避免在我的问题中忙着等待。

我想问一下java文档,免得麻烦,但是文档是这样的:

Acquires the given number of permits from this semaphore,
 blocking until all are available, or the thread is interrupted.
Acquires the given number of permits, if they are available,
 and returns immediately, reducing the number of available permits
 by the given amount.
If insufficient permits are available then the current thread
 becomes disabled for thread scheduling purposes and lies dormant

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html获得(int)

也就是说,文档似乎暗示了两个答案。哪一个是正确的?

我完全不明白这是在暗示你在忙着等待。它清楚地声明线程处于"禁用"和休眠状态。基本上,它很便宜:线程在等待获取信号量时不会消耗处理器时间。

由于这一行,显然是wait/notify:

如果可用的许可不足,则禁用当前线程用于线程调度目的,并且处于休眠状态。

这意味着操作系统不会调度线程,直到唤醒它的事件(可用信号量允许)发生,此时线程被通知继续执行。

最新更新