[英]Synchronize data between many threads
我是同步主題的新手,在嘗試訪問同步對象時,我找不到任何有關使用wait()
, notify()
和notifyAll()
方法的明確信息。 例如,如果我們有這樣的代碼:
class X extends Thread {
int x;
public void methodX()
{
synchronized(this)
{
//some operations on x
}
}
}
class Y extends Thread {
public void methodY(X x)
{
int z = x.x;
}
}
我們應該調用wait()
在methodY()
和notify()
在結束methodX()
否則,我們將不會為z
分配任何值,否則線程將在不顯式調用wait()
情況下wait()
直到X解鎖為止。
因此,假設您需要methodY
等到methodX
執行methodX
,一種有效的方法是wait
和notify
或notifyAll
。 當然,還有其他多種方法,但其中一種是有效的。 鑒於您甚至可能不需要同步塊。
void methodX(){
// do your work here
this.notifyAll();
}
void methodY(X x){
x.wait();
int x = X.x;
}
您可能考慮將阻塞代碼放入X
的getX
方法中,但是上述方法在IF起作用(並且這是BIG IF)時,您可以保證methodY
在methodX
之前啟動,因為否則, methodY
將丟失notify
調用。
綜上所述,我同意JB Nizet
,您可以考慮使用更高級的機制,例如Semaphore / Mutex /等。這些機制可以簡化復雜性。 例如,如果您使用CountDownLatch
並以1計數創建它,則您的代碼可能會更健壯...
考慮:
class X{
volatile int x;
final CountDownLatch cdl = new CountDownLatch(1);
void methodX(){
// do work here
cdl.countDown();
}
int getX(){
cdl.await();
return x;
}
}
class Y{
void methodY(X x){
int z = X.getX();
}
}
以上內容將每次都有效,沒有任何訂購風險。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.