我有一個程序,擲骰子,並使用一個新的線程來循環,以更新圖像和重繪。這裏是我的代碼:Java同步對象,等待和通知
public int roll()
{
new Thread(
new Runnable() {
public void run() {
synchronized(o) {
o.notify();
for (int i = 0; i < 10; i++) {
image = randomImage();
repaint();
try {
Thread.sleep(100);
}
catch(InterruptedException ex) {
System.out.println("InterruptedException caught");
}
}
}
}
}
).start();
synchronized(o) {
try {
o.wait();
}
catch(InterruptedException ex) {
System.out.println("InterruptedException caught");
}
}
return rolled;
}
在我的其他類中,我有:
int rolled = dicePanel.roll();
label.setText("Rolled a + rolled");
的問題是,與同步當前的代碼,骰子圖像不動畫,但返回正確的int滾動。如果沒有同步代碼,圖像將生成動畫,但roll方法將返回0作爲整數,因爲它不會讓其他線程完成。
有什麼辦法讓圖像代碼循環遍歷並重新繪製每次,但是等到線程完成以返回int滾動?
第一條評論 - 當你剛剛獲得'o'上的鎖並打算保留它一段時間時,我無法在調用'o.notify()'時看到很多目的。 –