Stop and restart a already running thread

百般思念 提交于 2021-02-10 08:44:28

问题


The Thread should end if I press a button, which sets the isButtonPressed to true. My problem is, that if a want to start the thread with thread.start(runnable) by clicking the button, I get this: IllegalThreadStateException: Thread already started (I thought the thread was terminated after the break because the the loop is over, but it seems that I am wrong).

Thread thread = new Thread(runnable);
thread.start(runnable);

The runnable Runnable:

    Runnable runnable = new Runnable() {
    @Override
    public void run() {
        time = 10;
        for (int i = 10; i <= 10; i--) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    txt_Time.setText(String.valueOf(time));
                }
            });

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }

            if (isButtonPressed) {
                break;
            }

            if (time == 0) {
                resetVisibleState();
                break;
            } else {
                time--;
            }
        }
    }
};

Thanks for your help!


回答1:


Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);



回答2:


From my understanding you need to start a new thread. You cannot re-start a thread that has ran its course.

Since you are correctly stopping the old one via your isButtonPressed. You should just be able to start a new instance of the thread in its place




回答3:


Take a boolean variable and wrap the contents you need to run continusly in the thread with a while loop that runs forever till Run is set to false then on clicking the button set the variable to false, for example :-

volatile boolean run = true;
Thread t = new Thread()
{
   while(run)
   {
     // whatever is here runs till Run is false
   }
}
t.start();

/*now when the button is pressed just trigger Run as false and the thread will be ended
later call t.start() when you need to start the thread again.*/


来源:https://stackoverflow.com/questions/35461897/stop-and-restart-a-already-running-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!