-1
我想了解如何正確使用等待並通知沒有Semafor或CountdownLatch。讓我們舉一個簡單的例子Java併發 - 如何正確鎖定並釋放線程
Response call(long[] l)
{
final Response r = new Response();
Thread t = Thread.currentThread(); //get current thread
thread2(l,s -> {
response.setObject(s);
t.notify(); //wake up first thread
});
Thread.currentThread().wait(); //wait until method thread2 finishes
return response;
}
void thread2(long[] l, Consumer c)
{
//start new thread and call
c.accept(resultobject);
}
我的行爲是否可以接受?是否需要將.notify方法放入同步塊中?
沒有。永遠不要使用通知並等待線程對象。 – Savior
另外,'wait'和'notify'都要求調用線程擁有該目標對象上的監視器。 – Savior
請參閱Java教程:https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html wait()/ notify()機制是一種原始設施,應該用於非常具體方式來實現更高級別的同步對象。 –