Exception in thread "main" java.lang.IllegalThreadStateException
The same Thread cannot call the start method repeatedly.
Once a thread is started, it can never be restarted. Only a new thread can be started, and only once. A running thread or dead thread can be restarted.
Case number one:
public static void main(String[] args) {
Test test= new Test();
test.start();
test.start();
Case 2:
public static void main(String[] args) {
Test test= new Test();
test.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.start();
}
The above two cases will be reported incorrectly: the Exception in thread "main" java.lang.IllegalThreadStateException
following is a correct case:
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();
}
}