我正在尝试使用多线程模拟一个简单的恒温器。我在 lblDesiredTemp 和另一个标签上保存了所需的温度值来显示当前温度 lblCurrentTemp。当系统中有两个以上的活动线程时会出现此问题。正在等待的线程不会被唤醒!
这是我的方法:
'private synchronized void ApplySetting()
{
Thread tempetureUpdater = new Thread()
{
@Override
public synchronized void run()
{
txtLog.setText(txtLog.getText() + "\n" + this.getName());
try
{
while(!isDone)
this.wait();
}
catch (InterruptedException ex)
{
txtLog.setText(txtLog.getText() + "\n" + ex.getMessage());
}
int Max = Integer.parseInt(lblDesiredTemp.getText());
int Current = Integer.parseInt(lblCurrentTemp.getText());
txtLog.setText(txtLog.getText() + "\n" + Current + " to " + Max);
if(Current > Max)
{
isDone = false;
for (int i = Current; i > Max; i--)
{
lblGasStatus.setText("Off");
try
{
Thread.sleep(3000);
decreaseTemeture();
}
catch (InterruptedException ex)
{
txtLog.setText(txtLog.getText() + "\n" + ex.getMessage());
}
}
txtLog.setText(txtLog.getText() + "\n" + this.getName() + " done!");
isDone = true;
this.notifyAll();
}
else
{
isDone = false;
for (int i = Current; i < Max; i++)
{
lblGasStatus.setText("On");
try
{
Thread.sleep(3000);
increaseTemeture();
}
catch (InterruptedException ex)
{
txtLog.setText(txtLog.getText() + "\n" + ex.getMessage());
}
}
txtLog.setText(txtLog.getText() + "\n" + this.getName() + " done!");
isDone = true;
this.notifyAll();
}
// Report the result using invokeLater().
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
setEnabled(true);
}
});
}
};
tempetureUpdater.start();
}
有什么问题?!