注意:如果此wait和notify使用不正確的語法,請隨意編輯/註釋。Java子類使用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」粘到任何地方?
很難推斷甚至沒有編譯的多線程代碼。在提問之前請注意代碼。 –