I've been told that using Thread.Sleep()
is a bad solution at times that one would want to make some time interval within a loop of actions in a synchronized method.
On the other hand, I have two different threads which are active throughout the running time of my program and also one shared object and when I use Object.wait(long) in that shared object, it causes my GUI to freeze for some time.
what would be a better solution for this problem?
Update This portion of the code is including one of the threads which is starting in GUI:
class temperatureUp extends Thread
{
@Override
public void run()
{
while(true)
{
try
{
GBC.increaseTemp();
updateSystemStatus();
}
catch(Exception ex)
{
StringWriter w = new StringWriter();
ex.printStackTrace(new PrintWriter(w));
txtLog.setText(w + "\n" + txtLog.getText());
}
}
}
};
and this is the synchronized method in shared object, GBC:
public synchronized void increaseTemp() throws InterruptedException{
// don't increase the temperature if the boiler
// is not turned on...
while (!isBoilerOn)
wait();
// increase the current temperature
if ((currentTemp + 1) < MAX_TEMP && currentTemp < desiredTemp) {
Thread.sleep(2000); ///what should put here if not thread sleep?
currentTemp ++;
updateGasBoilerStatus();
}
}