2016-04-22 3 views
-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メソッドを同期ブロックに配置する必要がありますか?

+0

Nopeスレッドオブジェクトでnotifyとwaitを使用しないでください。 – Savior

+1

また、 'wait'と' notify'の両方は、呼び出し元スレッドがそのターゲットオブジェクト上のモニタを所有していることを要求します。 – Savior

+0

Javaチュートリアルを参照してください。https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html wait()/ notify()メカニズムは、非常に固有のより高いレベルの同期オブジェクトを実装する方法です。 –

答えて

2

はいnotifysynchronized blockに入力する必要があります。主なロジックは以下の通りです:

オブジェクトの特定の状態のために待機しているスレッドの擬似コード:

synchronized(mutex) { 
    while (object state is not the expected one) { 
     mutex.wait(); 
    } 
    // Code here that manipulates the Object that now has the expected state 
} 

オブジェクトの状態を変更するとしたいスレッドの擬似コード他のスレッドに通知する:

synchronized(mutex) { 
    // Code here that modifies the state of the object which could release 
    // the threads waiting for a given state 
    mutex.notifyAll(); 
} 
関連する問題