我有一个程序,掷骰子,并使用一个新的线程来循环,以更新图像和重绘。这里是我的代码: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()'时看到很多目的。 –