2016-04-22 124 views
-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方法放入同步塊中?

+0

沒有。永遠不要使用通知並等待線程對象。 – Savior

+1

另外,'wait'和'notify'都要求調用線程擁有該目標對象上的監視器。 – Savior

+0

請參閱Java教程:https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html wait()/ notify()機制是一種原始設施,應該用於非常具體方式來實現更高級別的同步對象。 –

回答

2

是的,需要將notify放入synchronized 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(); 
}