非法线程状态异常。

4

我正在编写一个多线程程序,在其中遇到了异常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;
    }


}
3个回答

3
在这个代码片段中:
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()。如文档所述,这是不合法的:

重复启动线程从来都不合法。特别地,执行完成的线程不能再次启动。

您可以将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]);
}

1

你不能两次启动同一个线程。如果你想创建多个线程,请将线程实例的创建移入循环中:

    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]);
    }

1

您正在尝试多次启动同一个(多)线程实例。在循环内创建Multithread的新实例,以便每个线程都获得自己的实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接