¿Podemos iniciar un hilo dos veces en Java? La respuesta es no, una vez que se inicia un hilo, no se puede reiniciar. Esto lanzará un archivo IllegalThreadStateException
. Echemos un vistazo al siguiente código:
public class ThreadTwiceExample implements Runnable { @Override public void run(){ Thread t = Thread.currentThread(); System.out.println(t.getName()+" is executing."); } public static void main(String args[]){ Thread th1 = new Thread(new ThreadTwiceExample(), "th1"); th1.start(); th1.start(); } }
Producción:
Exception in thread "main" th1 is executing. java.lang.IllegalThreadStateException
Como puede observar, la primera llamada a start () resultó en la ejecución del método run (), sin embargo, se lanzó la excepción cuando intentamos llamar a start () por segunda vez.