android - 如何随时停止运行线程并随时启动

标签 android multithreading

下面的代码仅启动线程一次,但我想通过调用下面的方法来停止并再次启动线程。

Thread th;
int t=45;

onstartbuttton()
{
th= new Thread(new callmymethod());
        th.start();
}
onstopbutton()
{
}

public class callmymethod implements Runnable {
        // TODO Auto-generated method stub

        @SuppressWarnings("null")
        @Override
        public void run() {
            // TODO Auto-generated method stub

            while(t>-1){

                try{

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub

                            time_btn.setText(""+t);

                            if(t==0)
                            {                               
                                Toast.makeText(getApplicationContext(), "Thread over", Toast.LENGTH_SHORT).show();

                            }
                        }
                    });Thread.sleep(1000);
                //  Log.i("Thread", "In run"+t);
                    t=t-1;

                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

现在我想停止线程,所以我必须在 onstopbutton() 方法中编写什么以及如何通过调用 onstartbutton() 方法重新启动。

最佳答案

您需要向线程添加一个标志,指示它应该停止运行。

您可以使用AtomicBoolean:

final AtomicBoolean flag = new AtomicBoolean();

onstartbuttton() {
    th= new Thread(new callmymethod(flag));
    flag.set(true);
    th.start();
}
onstopbutton() {
    flag.set(false); // indicate that the thread should stop
}

public class callmymethod implements Runnable {
    public AtomicBoolean flag;
    public callmymethod(AtomicBoolean flag) {
        this.flag = flag;
    }
    @Override
    public void run() {
        int t = 45;  // start back from 45
        while(t>-1 && flag.get()){
            // do as before
        }
    }
}

关于android - 如何随时停止运行线程并随时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23671487/

相关文章:

java - 如何在共享首选项中分配唯一的字符串值

android - 如何在 jetpack compose 中使用 PreviewView?

multithreading - 如何在应用程序关闭时终止 Delphi 中的匿名线程?

c++ - 单核cpu多线程的意义

java - 以下是线程安全的吗? 4个线程写入相同的数据结构

java - Retrofit 2 请求返回空对象引用

java - 新空白 Activity 出​​现空指针异常错误

java - 在后台发送电子邮件 - Android

c++ - 线程事件会在程序退出后自动关闭吗?

java - 即使在调用中断方法后线程也不会中断