How can I restart a thread in java / android using a button?

I have a thread in java / Android like this:

Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        update_i();
    }
};



@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    Thread myThread = new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    handler.sendMessage(handler.obtainMessage());
                    Thread.sleep(timer);
                } catch (Throwable t) {
                }
            }
        }
    });

    myThread.start();
}

The thread works fine when running my application. But I want to start / restart the stream using the button.

Button.OnClickListener StartButtonOnClickListener = new Button.OnClickListener() {
    @Override
    public void onClick(View v) {

        //start/restart the thread
    }
};

If I copy a thread to a button, I simply create a new thread every time the user clicks on the button. I want to start a thread when the user first clicks on the kill button and starts from the beginning if the user clicks the button a second time (I don’t want to start the second thread).

+3
source share
2 answers

You cannot restart Thread.

From the documentation:

Throws IllegalThreadStateException  
    if the Thread has been started before

, .


:

+6

, , , , , .

, instand , .

if(myThread.isAlive()){
    myThread.interrupt(); 
}
myThread = new MyThread();
myThread.start();

,

+11

Source: https://habr.com/ru/post/1767264/


All Articles