-4

I have searched about kill the Runnable but i could not find the true answer with this code.I have tried boolean and stop() method.Can somebody help me to kill this runnable? Thanks.

Runnable runnable = new Runnable() {
                  @Override
                  public void run() {

                      while(true) {
                      try {
                          Thread.sleep(1000);
                        } catch (InterruptedException e) {
                          e.printStackTrace();
                        }

                      MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myL.setBackgroundResource(R.drawable.close);

                        }
                    });
                      try {
                          Thread.sleep(1000);
                        } catch (InterruptedException e) {
                          e.printStackTrace();
                        }

                      MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                myL.setBackgroundResource(R.drawable.open);

                            }
                        });
                    }
                  }
                };
                new Thread(runnable).start();
Sefa
  • 29
  • 2
  • 9

2 Answers2

0

you can set your exit condition:

private class MyThread extends Thread {
  private boolean volatile exit = false;
   @Override
   public void run() {
     while(!exit) {
     }
   }

  public void stopMyThread() {
       exit = true;
  }

}

and from your code you call

 myThreadInstance.stopMyThread();

when you need to make you run method finish

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

You are repeating infinitely a one-second-wait. This will never stop. You need to have a boolean flag which will serve as the continue/stop condition and you need to negate its value when the Thread needs to stop.

If you want to stop it from another Thread, then call Thread.interrupt.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175