【问题标题】:Stop and restart a already running thread停止并重新启动已经运行的线程
【发布时间】:2025-01-11 04:35:02
【问题描述】:

如果我按下一个按钮,线程应该结束,这会将 isButtonPressed 设置为 true。 我的问题是,如果想通过单击按钮使用 thread.start(runnable) 启动线程,我会得到:IllegalThreadStateException: Thread already started(我认为线程在中断后终止因为循环结束了,但是好像我错了)。

Thread thread = new Thread(runnable);
thread.start(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--;
            }
        }
    }
};

感谢您的帮助!

【问题讨论】:

  • 添加到 Andrew 的答案,使用执行器服务而不是重新启动一个新线程。看看这个问题:*.com/questions/36398144/…

标签: java android multithreading


【解决方案1】:

Java 线程不可重新启动。对于您想要实现的目标,您可以每次都创建一个新线程,或者您可以查看ExecutorService。只需创建一个单线程执行器 (Executors.newSingleThreadExecutor),并在每次需要运行时将可运行文件提交给它。

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

【讨论】:

  • 你很棒。非常感谢你
【解决方案2】:

据我了解,您需要开始一个新线程。您无法重新启动已运行的线程。

由于您通过isButtonPressed 正确地停止了旧的。您应该能够在其位置启动线程的新实例

【讨论】:

    【解决方案3】:

    获取一个布尔变量并将您需要在线程中连续运行的内容包装在一个 while 循环中,该循环将永远运行,直到 Run 设置为 false,然后单击按钮将变量设置为 false,例如:-

    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.*/
    

    【讨论】:

    • 虽然这可能是对该问题的有效答案,但建议将 run 声明为 volatile boolean。当线程开始运行时,它将缓存来自周围范围的标志。据我所知,实际刷新值的时间完全取决于操作系统,并且可能需要很长时间。
    最近更新 更多