简体   繁体   English

在android中重复启动和停止一个线程

[英]start and stop a thread repeatedly in android

Here i have a method called Method1(), which will start a thread when the method is called odd time and stop same called even time. 这里我有一个名为Method1()的方法,它将在方法被称为奇数时间时启动一个线程并停止相同的称为偶数时间。 The below snippet works when i called the method through Button.onClick event. 当我通过Button.onClick事件调用该方法时,下面的代码段工作。 Is this the correct approach to pause and resume the thread ? 这是暂停和恢复线程的正确方法吗? Is my approach thread safe ? 我的方法线程安全吗?

Thread sampleThread = null;
..
..
..
private void Method1(){

    if(sampleThread == null){

        sampleThread =   new Thread(){
            @Override
            public void run() {

                while(true) {

                    Log.d(TAG,"Inside Thread");

                }
            }
        };
        sampleThread.start();

    }else {

        sampleThread.interrupt();

    }
}

You can use a boolean variable and set it for the while loop. 您可以使用布尔变量并将其设置为while循环。 like this. 像这样。

Boolean isActive = true;

then, 然后,

while(isActive ) {
   Log.d(TAG,"Inside Thread");
}

So, when you change the isActive to false then the thread will stop. 因此,当您将isActive更改为false时,线程将停止。

If Method1 will be called frequently,I suggest you'd better set a flag,enable it to resume thread,and disable it to pause thread.because if you create and destroy a thread frequently,many CPU and memory will be wasted.You can use like this: 如果经常调用Method1 ,我建议你最好设置一个标志,让它恢复线程,并禁用它来暂停线程。因为如果你经常创建和销毁一个线程,很多CPU和内存将被浪费。你可以使用这样:

public class MyThread extends Thread{
        volatile boolean isRunning = true;//make sure use volatile keyword
        @Override
        public void run() {

            while(isRunning) {

                Log.d(TAG,"Inside Thread");

            }
        }
        public void setRunning(boolean running){
            this.isRunning = running;
        }
    };

and when you want to pause,call thread.setRunning(false) ,to restart it,call thread.setRunning(true) 当你想暂停时,调用thread.setRunning(false) ,重新启动它,调用thread.setRunning(true)

If not so frequently,your solution almostly is ok,but I think you should add 如果不是那么频繁,你的解决方案几乎没问题,但我认为你应该补充一下

sampleThread = null

after sampleThread.interrupt(); sampleThread.interrupt(); ,otherwise when you next pause it,it will interrupt a non-active thread,maybe there will throw an exception. ,否则当你下次暂停它时,它会中断一个非活动线程,可能会抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM