我使用 ReentrantLock
和 Condition
来同步两个线程。每当消费者线程在生产者线程执行 signal()
之前对条件执行 await()
时,一切似乎都工作正常。但是,当生产者线程在消费者线程执行 await()
之前执行 signal()
时,消费者线程就会永远等待。这是应该发生的还是我做错了什么?当发出条件信号并且没有等待线程时,预期的行为是什么?
这是消费者的代码:
this.lock.lock();
Log.d("websocket", "Sender acquired lock");
try
{
Log.d("websocket", "Sender waiting for message from server");
this.resultReady.await();
Log.d("websocket", "Sender waking up");
return this.result;
} catch (InterruptedException e)
{
e.printStackTrace();
}
finally {
this.lock.unlock();
}
这是生产者的代码:
Log.d("websocket", "Receiver acquiring lock");
this.lock.lock();
Log.d("websocket", "Receiver acquired lock");
try
{
Log.d("websocket", "Receiver setting result");
result = serviceResult;
Log.d("websocket", "Receiver waking up waiting threads");
this.resultReady.signal();
} finally
{
this.lock.unlock();
}
最佳答案
Is this supposed to happen or am I doing something wrong? What is the expected behaviour when a condition is signalled and there are no waiting threads?
这应该会发生。如果没有线程等待,则没有任何效果。 Java 文档说:
Wakes up one waiting thread.
If any threads are waiting on this condition then one is selected for waking up. That thread must then re-acquire the lock before returning from await.
如果没有线程唤醒,那么就没有效果吗?
您有一个缓冲区,其中包含一项,即您的结果
。您必须测试此结果是否独立于 await()
方法而有效。或者切换到诸如Semaphore
之类的东西,它确实有一个可以设置的内部状态。
// Consumer
this.lock.lock();
Log.d("websocket", "Sender acquired lock");
try
{
Log.d("websocket", "Sender waiting for message from server");
while( result == null ) // CHANGE HERE
resultReady.await();
Log.d("websocket", "Sender waking up");
return this.result;
} catch (InterruptedException e)
{
e.printStackTrace();
}
finally {
this.lock.unlock();
}
关于java - 没有等待线程的信号条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219841/