Java – Start and stop a thread repeatedly in Android

Start and stop a thread repeatedly in Android… here is a solution to the problem.

Start and stop a thread repeatedly in Android

Here I have a method called Method1() that will start a thread when the method is called at odd time and stop the method at even time. When I call the method via the Button.onClick event, the following code fragment works. Is this the right way to pause and resume threads? Is my method 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();

}
}

Solution

If Method1 is called frequently, I suggest you’d better set a flag that enables it to resume threads and disable it to pause threads. Because if you create and destroy threads frequently, a lot of CPU and memory will be wasted. You can use it like this:

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;
        }
    };

When you want to pause, call thread.setRunning (

false), restart it, call thread.setRunning (true).

Your solution is almost fine if not so often, but I think you should add it

sampleThread = null

In sampleThread.interrupt(); After that, otherwise the next time you pause it, it interrupts a non-active thread and may throw an exception.

Related Problems and Solutions