Question

The below code is starting the thread only once, but I want to stop and start thread again by calling below method.

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

Now I want to stop thread, so what I have to write in onstopbutton() method and how to start again by calling onstartbutton() method.

Was it helpful?

Solution

You need to add a flag to your thread indicating that it should stop running.

You can use an 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
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top