Java信号量是否使用忙等待或默认等待/通知?

时间:2011-12-25 17:29:11

标签: java multithreading semaphore

问题如下。我在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#acquire(int

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

2 个答案:

答案 0 :(得分:1)

我看不出它是如何暗示忙碌的等待。它清楚地表明该线程被“禁用”并处于休眠状态。基本上,它很便宜:线程在等待获取信号量时不会消耗处理器时间。

答案 1 :(得分:0)

由于这条线明显等待/通知:

  

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

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