Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop threads created with an anonymous class?

In my program I have many threads in a working state, started in the method run or by calling other method from run. What is the method to stop these threads?

The threads are started as:

Runnable r = new Runnable() {
   @Override
      public void run() {
         // do something...
      }
};
new Thread(r,"Thread_1").start();

Another one may be like:

Runnable r = new Runnable() {
   @Override
      public void run() {
         startThread(); // another method called
      }
};
new Thread(r,"Thread_2").start();

What is the method of stopping thread_1 and thread_2?

UPDATE

What I want is when I click on a button deactivate 3-4 threads working behind should get deactivated so that the user can again start those threads by again assigning a task.

like image 398
program-o-steve Avatar asked Dec 11 '11 13:12

program-o-steve


2 Answers

Thread.stop() is very dangerous, it's strongly recommended that you avoid it, for the reasons stated in the javadoc.

Try passing a message into the Runnable, perhaps using something like this:

final AtomicBoolean terminate = new AtomicBoolean(false);

Runnable r = new Runnable() {
   @Override
   public void run() {
      while (!terminate.get()) {
         // do something...
      }
   }
};

new Thread(r,"Thread_1").start();
// some time later...
terminate.set(true);

You'd have to figure out a way to scope the variables to allow this to compile under your setup. Alternatively, extend Runnable with your interface which has a cancel() method (or whatever), which your anonymous classes have to implement, which does a similar sort of thing with the loop check flag.

interface CancellableRunnable extends Runnable {
   void cancel();
}

CancellableRunnable r = new CancellableRunnable() {    
   private volatile terminate = false;

   @Override
   public void run() {
      while (!terminate) {
         // do something...
      }
   }

   @Override
   public void cancel() {
      terminate = true;
   }
}

new Thread(r,"Thread_1").start();
// some time later...
r.cancel();
like image 104
skaffman Avatar answered Sep 20 '22 18:09

skaffman


Thread class has method stop() introduced in java 1.0 and deprecated in java 1.1. This method still works and kills thread. So, you can stop all your threads if you want.

But this is very not recommended. The reason is described in javadoc of Thread.stop(). So the best solution is to fix the implementation of your threads to make them exit correctly. But if it is not possible (e.g. if this is not your code) and you still need this very much use Thread.stop().

like image 22
AlexR Avatar answered Sep 21 '22 18:09

AlexR