[英]Java sub-class updateting with wait-notify
注意:如果此等待和通知使用不正確的語法,請隨時進行編輯/注釋。
您有一個類,該類的計算只能由其他線程完成:
class Foo{
public Foo() {
//so thread 2 can know about us. So much for design patterns.
synchronized(GlobalStuff) {GlobalStuff.threadpool.add(this);}
}
Bar b;
public Bar emptyBar() { //called by thread #1 ("your" thread).
synchronized(this) {
b = new Bar();
return b;
}
}
public void makeTest() { //Thread #2 periodically runs this block of code.
synchronized(this) {
if (b==null) {return;} //do nothing if it is still null.
if (b.hasBeenMadeIntoExam();) {return;} //do nothing if it is done already.
b.makeMeAnAnnoyingExam();
....
this.notifyAll(); //do we even need the "this"?
}
}
}
這是您的等待方式:
//thread 1 runs this block of code.
Foo fooey = new Foo();
Bar b = fooey.emptyBar();
while( b.equals(fooey.emptyBar()) ) { //some statement to check whether it is done or not
try { //mandatory try catch statements to keep Java verbose.
fooey.makeTest();
fooey.wait(); //wait, and fooey will free us when it calls notifyAll()
} catch (InterruptedException ex) {}
}
.... //more code that depends on the exam being made.
我擔心的是b的字段不是可變的(即使我們將b更改為可變的),因此當線程2更新它們時,它們不會立即出現在線程1中。請記住,同步和通知不是“深”的,因此它們不要一味地更新所有子類的狀態。 我需要擔心嗎? 有沒有一種方法可以解決此問題,而無需在各處手動添加“ volatile”?
我通常避免使用“ this”進行同步。 而不是使用sync(this),而是定義一個顯式鎖並對此進行同步。 如果子類需要它,則也可以將其提供給他們。 例如
class Foo {
protected final Object lock = new Object();
public Bar emptyBar() {
synchronized (lock) {
...
}
}
...
}
而不是this.notifyAll(),請使用lock.notifyAll();。
只要您要在Synchronized(lock)塊內訪問/更新要讀取/寫入的所有字段,就可以放心這些值是最新的。
而不是同步整個實例。 您只能同步方法。
酒吧b; 公共同步Bar emptyBar(){//由線程1(“您的”線程)調用。 b =新的Bar(); 返回b; }
而不是在Foo中添加synchronized
塊。 您可以在Bar中synchronize
更改對象狀態的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.