1

Im trying to create 4 threads and give them tasks to do. However I keep getting IllegalThreadStateException. I lurked questions here but none seem to help me. Heres the crucial code fragment:

Sorter worker1 = new Sorter(theView,1);
Sorter worker2 = new Sorter(theView,2);
Sorter worker3 = new Sorter(theView,3);
Sorter worker4 = new Sorter(theView,4);

for(int nextTask=0 ; nextTask<List_of_FileContentsLists.size() ; nextTask++){
    if(worker1.busy == false){
        worker1.acquireTask(List_of_FileContentsLists.get(nextTask),fileList[nextTask]);
        worker1.start();
    }
    else if(worker2.busy == false){
        worker2.acquireTask(List_of_FileContentsLists.get(nextTask),fileList[nextTask]);
        worker2.start();
    }
    else if(worker3.busy == false){
        worker3.acquireTask(List_of_FileContentsLists.get(nextTask),fileList[nextTask]);
        worker3.start();
    }
    else if(worker4.busy == false){
        worker4.acquireTask(List_of_FileContentsLists.get(nextTask),fileList[nextTask]);
        worker4.start();
    }
    else{
        nextTask--;
    }
}

Thanks in advance!

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 1
    [Is it legal to call the start method twice on the same Thread?](https://stackoverflow.com/questions/1215548/is-it-legal-to-call-the-start-method-twice-on-the-same-thread) – rgettman May 10 '18 at 16:08
  • Duplicate of https://stackoverflow.com/questions/1215548/is-it-legal-to-call-the-start-method-twice-on-the-same-thread – Raedwald May 11 '18 at 09:33

2 Answers2

2

For every worker that you start once, you cannot start it repeatedly as you have done through your looping. I am hoping that the WorkerN stands for different threads.

IllegalThreadState arises when you try to change thread's state to the state not allowed. For more reference, go through the javadoc:

https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalThreadStateException.html

Pang
  • 9,564
  • 146
  • 81
  • 122
Rajan Singh
  • 309
  • 2
  • 7
1

If List_of_FileContentsLists.size() > 1, you will get IllegalThreadStateException

For example sake, assume that List_of_FileContentsLists.size() = 2 and worker1.busy = false.

When nextTask is 0, you have started the thread since 0 < 2.

In second iteration, nextTask is 1 and still 1 < 2.

As per your logic, you try to start() a thread, which has been already started.

start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

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

Suggestions:

  1. Don't call start() method more than once. Change your for loop accordingly.

  2. Start an ExecutorService and post Runnable or Callable task to ExecutorService.

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211