gpt4 book ai didi

java - 非法线程状态异常

转载 作者:搜寻专家 更新时间:2023-11-01 02:52:06 27 4
gpt4 key购买 nike

我正在编写一个多线程程序,其中出现异常 java.lang.IllegalThreadStateException

欢迎任何帮助

这是我的堆栈跟踪

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at GeoMain.main(GeoMain.java:18)

这是我的主类代码

    public class TMain {

public static void main(String[] args) {

String Batchid="1,2,3";
String batch[]=StringUtils.split(Batchid,",");

MultiThread gt=new MultiThread();
for(int i=0;i<batch.length;i++){
gt.setBatch(batch[i]);
gt.start();
System.out.println("Thread started for "+batch[i]);
}

System.out.println("mainfinish");

}

}

这是我的多线程类

public class MultiThread extends Thread {

private static Queue<String> queue = new LinkedList<String>();
private static Boolean isInUse = false;

private void runcoder()
{
String batchid=null;
BatchIdCreator bid=null;
while(isInUse)
{
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
System.out.println("exception");
e.printStackTrace();
}
}
isInUse=true;

synchronized(isInUse)
{

isInUse=true;
batchid=queue.poll();
System.out.println(batchid);
System.out.println(batchid);
bid=new BatchIdCreator(batchid);
// get a list from database
bid.getList();
// print on console
bid.printList();
isInUse=false;
}
}

@Override
public void run() {
runcoder();
}

public void setBatch(String batchid)
{
queue.add(batchid);
}

public static Boolean getIsInUse() {
return isInUse;
}


}

最佳答案

在这段代码中:

MultiThread gt=new MultiThread();
for(int i=0;i<batch.length;i++){
gt.setBatch(batch[i]);

gt.start(); <--- Same thread object as in previous iteration

System.out.println("Thread started for "+batch[i]);
}

您在同一个线程上一遍又一遍地调用 start()。如 the documentation 中所述,这是非法的:

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

您可能希望将 new MultiThread() 移动到循环中以避免这种情况:

                                     ----------.
for(int i=0;i<batch.length;i++){ |
|
MultiThread gt=new MultiThread(); <--'

gt.setBatch(batch[i]);
gt.start();
System.out.println("Thread started for "+batch[i]);
}

关于java - 非法线程状态异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274847/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com