Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.IllegalThreadStateException

I am working with threads. However when I try to start a thread, I get a Exception. In concrete java.lang.IllegalThreadStateException. My code is:

public void readCommand() {     readThread = new Thread("Thread for reading") {         public void run() {             while (running) {                 readBuffer = usbservice.receiveData();                 put(readBuffer);             }         }     };     readThread.start(); } 

What could the problem be?

like image 695
Jose Hdez Avatar asked Sep 06 '11 06:09

Jose Hdez


2 Answers

You are storing the thread in a field. If the method is called in two threads, the readThread.start() can be called twice for the same thread. You need to ensure readCommand is not called multiple times and perhaps not start the readThread again if its already running. e.g. you can synchronized the method and check readThread before you start.

like image 116
Peter Lawrey Avatar answered Sep 21 '22 13:09

Peter Lawrey


A thread will throw the exception when calling start if the thread's state (as retrieved by Thread.currentThread().getState() is anything other than NEW.

The source;

public synchronized void start() {     /*      * A zero status value corresponds to state "NEW".      */     if (threadStatus != 0)         throw new IllegalThreadStateException();     group.add(this);     start0();     if (stopBeforeStart) {         stop0(throwableFromStop);     } } 

This means, your thread is in one of the other states, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED.

You could have a look at the state of the threads via a thread dump or JConsole to see what yours is doing. You can programmatically take a thread dump right before the call to start using something like tempus-fugit if that helps.

UPDATE: In response to your comments, if you interrupt a thread which in your case, I assume will set the running flag to false, the thread will still be RUNNABLE. To 'resume' work on the thread (again, I'm assuming that's what you want to do), you would change the running flag again. Calling start will fail because it's already started. You could also let the thread die on interruption and then just create a new instance of a Thread and "start" that one as an alternative.

like image 37
Toby Avatar answered Sep 22 '22 13:09

Toby