-1
SemaforやCountdownLatchを使わずにwaitとnotifyを正しく使用する方法を理解したいと思います。簡単な例があります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メソッドを同期ブロックに配置する必要がありますか?
Nopeスレッドオブジェクトでnotifyとwaitを使用しないでください。 – Savior
また、 'wait'と' notify'の両方は、呼び出し元スレッドがそのターゲットオブジェクト上のモニタを所有していることを要求します。 – Savior
Javaチュートリアルを参照してください。https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html wait()/ notify()メカニズムは、非常に固有のより高いレベルの同期オブジェクトを実装する方法です。 –