Me han dicho que utilizar Thread.Sleep()
es una mala solución a veces que uno quisiera hacer un intervalo de tiempo dentro de un bucle de acciones en un método sincronizado.Thread.Sleep alternativa en Java
Por otro lado, tengo dos subprocesos diferentes que están activos durante el tiempo de ejecución de mi programa y también un objeto compartido y cuando uso Object.wait (long) en ese objeto compartido, causa que mi GUI se congele durante algún tiempo.
¿cuál sería una mejor solución para este problema?
actualización Esta parte del código está incluyendo uno de los hilos que está comenzando en 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()); } } } };
y este es el método sincronizado en objeto compartido, 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();
}
}
Debe estar causando que [la secuencia de distribución de eventos] (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) espere. ¿Podría proporcionar un pequeño ejemplo en el código de cómo inicia sus hilos y cuándo llama a wait()? – theon
Eche un vistazo a ['SwingWorker'] (http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html). Además, vea ['this answer'] (http://stackoverflow.com/a/11546203/597657) para saber cómo está funcionando. –
@theon Actualicé la publicación y agregué una parte del código. – Afflatus