IllgalThreadStateException

I am writing a multi-threaded program in which I get a java.lang.IllegalThreadStateException exception.

Any help would be appreciated.

here is my stack trace

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

here is my code for the main class

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

and here is my multithreading class

 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; } } 
+4
source share
3 answers

In this snippet:

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

you call start() over and over in the same thread. As described in the documentation , this is illegal:

Cannot start a thread more than once. In particular, the thread cannot be restarted after completion of execution.

You can move new MultiThread() in a loop to avoid this:

  ----------. 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]); } 
+3
source

You cannot start the same thread twice. You want to create multiple threads by moving the thread instance creation to the loop:

  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
source

You are trying to start the same instance of (Multi) Thread several times. Create a new instance of Multithread inside the loop, so each thread gets its own instance.

0
source

Source: https://habr.com/ru/post/1396368/


All Articles