Exception in thread "main" java.lang.IllegalThreadStateException
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();
}
}