Reputation: 115
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!
Upvotes: 1
Views: 1141
Reputation: 324
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
Upvotes: 2
Reputation: 38910
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.
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:
Don't call start()
method more than once. Change your for
loop accordingly.
Start an ExecutorService
and post Runnable
or Callable
task to ExecutorService
.
Upvotes: 1