android – When I run Thread second time: java.lang.IllegalThreadStateException: Thread already started-ThrowExceptions

Exception or error:

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.

How to solve:

You should check state of that thread before starting it.

if (thread.getState() == Thread.State.NEW)
{
     thread.start();
}

###

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.

###

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).

Leave a Reply

Your email address will not be published. Required fields are marked *