-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()机制是一种原始设施,应该用于非常具体方式来实现更高级别的同步对象。 –