-
-
Save parzibyte/48870ede0f6fbbbd3b07a988093e0d25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Ejemplo con Runnable y Thread para ejecutar código cada cierto | |
tiempo en Java | |
@author parzibyte.me | |
*/ | |
class Main { | |
public static void main(String[] args) { | |
Runnable runnable = new Runnable() { | |
@Override | |
public void run() { | |
// Esto se ejecuta en segundo plano una única vez | |
while (true) { | |
// Pero usamos un truco y hacemos un ciclo infinito | |
try { | |
// En él, hacemos que el hilo duerma | |
Thread.sleep(1000); | |
// Y después realizamos las operaciones | |
System.out.println("Me imprimo cada segundo"); | |
// Así, se da la impresión de que se ejecuta cada cierto tiempo | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}; | |
// Creamos un hilo y le pasamos el runnable | |
Thread hilo = new Thread(runnable); | |
hilo.start(); | |
// Y aquí podemos hacer cualquier cosa, en el hilo principal del programa | |
System.out.println("Yo imprimo en el hilo principal"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment