Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I run Thread second time: java.lang.IllegalThreadStateException: Thread already started [duplicate]

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.

like image 453
drozdzynski Avatar asked Apr 11 '14 08:04

drozdzynski


2 Answers

You should check state of that thread before starting it.

if (thread.getState() == Thread.State.NEW)
{
     thread.start();
}
like image 194
The Holy Coder Avatar answered Oct 05 '22 23:10

The Holy Coder


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.

like image 28
Yuvaraja Avatar answered Oct 05 '22 22:10

Yuvaraja