简体   繁体   English

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

[英]Do Java semaphores use busy waiting or a wait/notify by default?

As the question goes. 问题是这样的。 I'm using the JDK 6.0 on Windows 7, and am attempting to use semaphores as a mechanism to solve a synchronization problem. 我在Windows 7上使用JDK 6.0,并尝试使用信号量作为解决同步问题的机制。 It works perfectly, but I'm trying to avoid busy waiting in my problem. 它工作得很好,但我试图避免忙于等待我的问题。

I would just ask the java documentation and spare SO the trouble, but the docs go like this: 我只想问一下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 ) http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html#acquire(int

That is to say, the docs seem to be implying both answers. 也就是说,文档似乎暗示了两个答案。 Which one is correct? 哪一个是正确的?

I don't see how it's implying busy-waiting at all. 我看不出它是怎么意味着忙着等待的。 It clearly states that the thread is "disabled" and dormant. 它清楚地表明该线程被“禁用”并处于休眠状态。 Basically, it's cheap: the thread won't consume processor time while it's waiting to acquire the semaphore. 基本上,它很便宜:线程在等待获取信号量时不会消耗处理器时间。

It's clearly wait/notify due to this line: 由于这条线,它显然是等待/通知:

If insufficient permits are available then the current thread becomes disabled for thread scheduling purposes and lies dormant. 如果没有足够的许可证,那么当前线程将被禁用以进行线程调度并处于休眠状态。

This means the thread is not scheduled by the OS until the event to wake it up (available semaphore permits) occurs, at which point the thread is signaled to continue execution. 这意味着操作系统不会调度线程,直到唤醒它的事件(可用信号量允许)发生,此时线程被发出信号以继续执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM