Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created February 27, 2019 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/48870ede0f6fbbbd3b07a988093e0d25 to your computer and use it in GitHub Desktop.
Save parzibyte/48870ede0f6fbbbd3b07a988093e0d25 to your computer and use it in GitHub Desktop.
/*
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