20

I have Thrad and Handler:

Handler handler = new Handler() {
    @Override
    public void handleMessage(android.os.Message msg) {
        super.handleMessage(msg);
        //do somethink
    }
};

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        //do somethink
        msg.obj = 1;
        handler.sendMessage(msg);
        thread.interrupt();
    }
});

When app start, at first time thread.start(); all work fine. But when I try start thread.start(); second time from button I have:

E/MessageQueue-JNI﹕ java.lang.IllegalThreadStateException: Thread already started.

drozdzynski
  • 1,239
  • 2
  • 13
  • 17
  • also an ans here http://stackoverflow.com/questions/13538668/stop-thread-and-again-start-giving-illegalthreadstateexception-in-blackberry – dev2d Apr 11 '14 at 08:39

3 Answers3

38

You should check state of that thread before starting it.

if (thread.getState() == Thread.State.NEW)
{
     thread.start();
}
Manish Dubey
  • 4,206
  • 8
  • 36
  • 65
4

Its not a good Idea to start a Thread more then once. You have to check Whether a Thread is already started or not. if Thread not started yet

if(!thread.isAlive()){
thread.start();
}

The Better Idea is to Create new Thread instance.

Yuvaraja
  • 715
  • 6
  • 22
  • 6
    i think there should be ! in `if(!thread.isAlive())...` but finished thread is not in state `NEW` and not alive at same time, so the exception can still occure – Zavael Nov 22 '14 at 15:58
  • 1
    thread.isAlive() is prone to "IllegalThreadStateException: Thread already started" - better use thread.getState(). – Kozuch Jan 26 '18 at 14:01
  • Tried it, still not working. – mrek May 02 '18 at 13:44
0

At the end of run(), your thread dies. If you want to keep it alive, then add a blocking queue to the thread and make run() a big while loop that reads from the queue. Instead of calling start for each message, just add it to the queue instead.

Of course, you still have to call start() once (when your program initializes).

Ted Bigham
  • 4,237
  • 1
  • 26
  • 31