在Java中,我收到此异常:
线程“主”中的异常java.lang.IllegalThreadStateException
这是代码:
class Worker extends Thread
{
public void run() {
System.out.println("#");
}
}
class Seconda extends Thread
{
public void run() {
System.out.println("*");
}
}
public class First
{
public static void main(String args[]) {
int contatore=0;
Worker prova = new Worker();
Seconda prova2 = new Seconda();
prova.start();
prova2.start();
for(;;) {
if(!prova.isAlive()) { prova.start();
contatore++;
}
if(!prova2.isAlive()) { prova2.start();
contatore++;
}
if(contatore==50) System.out.println("");
}
}
}
异常是什么意思?
最佳答案
您正在尝试启动一个已经启动的线程。
您需要做的是在for循环中创建prova和prova2?
public static void main(String args[]) {
int contatore=0;
//Worker prova = new Worker();
//Seconda prova2 = new Seconda();
//prova.start();
//prova2.start();
for(;;) {
Worker prova = new Worker();
Seconda prova2 = new Seconda();
if(!prova.isAlive()) {
prova.start();
contatore++;
}
if(!prova2.isAlive()) {
prova2.start();
contatore++;
}
if(contatore==50) System.out.println("");
}
}