1

Consider this example:

Thread thread = new Thread(new Runnable() {
    public void run() {
      // Sleep for 5000ms
      // Show toast message
    }
  });

Now I will start this thread on button click in MainActivity and right after that I would exit the activity on back button press, but in overided method onBackPressed following code is implemented:

If(thread != null)
   thread.interupt();
finish();

After few seconds toast message is shown, why is that?

Bruno
  • 3,872
  • 4
  • 20
  • 37
Munez NS
  • 1,011
  • 1
  • 12
  • 31
  • [HERE](http://stackoverflow.com/questions/5008176/thread-interrupt-doesnt-work) and [HERE](http://stackoverflow.com/questions/9791361/thread-not-interrupting) you will find some explanations. consider using `AsyncTask` in Android – snachmsm Jun 25 '15 at 07:04

2 Answers2

1

interrupt, clears the interrupt status of your thread and will cause the InterruptedException to be thrown. So if your thread is sleepin, and while it is asleep, you call interrupt, it will be woken up, and the execution flow will continue from the instruction that follows the catch block. Assuming you have something really simple like:

public void run() {
   try {
      Thread.sleep(500);
   } catch (InterruptedException e) {
      e.printStackThreace();
   }
   runOnUiThread(TOAST);
}

or

public void run() {
   while(true) {
      try {
         Thread.sleep(500);
      } catch (InterruptedException e) {
         e.printStackThreace();
      }
      runOnUiThread(TOAST);
   }
}

both will shown the Toast even though you called interrupt()

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

While blackbelt has already explained the reason why this happens, here is how you can get around the problem.

The best way to interupt a thread is to use a if-boolean-break method. So if i were to re-write you code it would be along the following lines

onBackPressed:

isBackPressed = true;

inside the thread's run method:

    Thread thread = new Thread(new Runnable() {
       public void run() {
         // Sleep for 5000ms
         if(!isBackPressed){
          // Show toast message
         }
       }
    });
Community
  • 1
  • 1
Umesh
  • 4,406
  • 2
  • 25
  • 37