Excepción en el hilo "main" java.lang.IllegalThreadStateException 错误

Exception in thread "main" java.lang.IllegalThreadStateException

Inserte la descripción de la imagen aquí
El mismo hilo no puede llamar al método de inicio repetidamente.
Una vez que se inicia un subproceso, nunca se puede reiniciar. Solo se puede iniciar un nuevo hilo, y solo una vez. Se puede reiniciar un hilo en ejecución o un hilo muerto.

Caso 1:

public static void main(String[] args) {
        Test test= new Test();
        test.start();
        test.start();

Caso 2:

public static void main(String[] args) {
        Test test= new Test();
        test.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        test.start();
    }

Los dos casos anteriores se informarán incorrectamente: Exception in thread "main" java.lang.IllegalThreadStateException
el siguiente es un caso correcto

 public static void main(String[] args) {
        //声明一个Thread类型的List集合
        List<Thread> thread = new ArrayList<>();
        Test test = new Test();
        for (int i = 0; i < 5; i++) {
         //每次new一个新的线程Thread,将对象test放进去  此处有5个线程
            thread.add(new Thread(test,"thread"+i));
        }
        for (int i = 0; i < 5; i++) {
            thread.get(i).start();
        }
    }
Publicado 15 artículos originales · elogiado 18 · visitas 358

Supongo que te gusta

Origin blog.csdn.net/qq_41490938/article/details/105499767
Recomendado
Clasificación