0

I have 2 classes, fe Class1 and Class2

let's say i do this in Class1:

Class2 class2 = new Class2();
Thread thread = new Thread(class2);
thread.start();
...
thread.stop();

now I want to check in the run method of Class2 when my thread stops, How can I do this? So when class1 stops the thread, I want to get some alert to class2 that it stopped and then do some things

user999379
  • 411
  • 1
  • 6
  • 12

4 Answers4

5
  1. Don't use stop(), use interrupt().

  2. If you obey point 1, in Class2 you can use:


public void run() {
  if(Thread.currentThread().isInterrupted())
    //somebody interrupted me, ouch!
}
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

First and foremost do not use thread.stop() as it is deprecated. Hence depending on such methods is not advisable. Second : There are multiple ways of solving it ie basically trying to shutdown or communicate.

  1. Use a Flag which notifies your message. But make sure the whole call is thread safe. And timely keep checking flag has been set or not. If set then do desired action.
  2. Interrupts are a perfect way of notifying other thread. Maintain and interruption policy say: that when ever an interrupt is thrown at thread A, and the interruption policy of A is to shutdown. ie whenever it receives an interrupt. Make runnable in A such that it timely checks for the interrupt and if the interrupt is set close the service then. Check status by Thread.currentThread().isInterrupted() Normally interrupts are primarily used for notifying others that it is requesting it to shutdown. (Brian Goetz "Concurrency in Practice" has an excellent chapter on it).
Jatin
  • 31,116
  • 15
  • 98
  • 163
  • 3
    The main reason why Thread.stop() should not be used is not the fact that it's deprecated, but the reason *why* it was deprecated: it can leave the application in an inconsistent state because it cannot be implemented in a way that respects consistency guarantees in the code. – Michael Borgwardt Oct 21 '11 at 11:56
  • http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html is an excellent reference on why it was deprecated. – Jatin Oct 21 '11 at 12:06
0

Once the thread has "stopped" that means that the run method is Class2 has exited. Therefore there is not a way to have code in the run method that executes after the thread has stopped.

You can listen for an interrupt and handle that, but this processing would be done while the thread is still running.

You can also have a different method in Class2 which you could call from Class1 once the thread has stopped.

John B
  • 32,493
  • 6
  • 77
  • 98
0

Your class2 should get an InterruptedException and that's it. BTW http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#stop()

Out of interest, what is it that you are trying to achieve?

Ravi Bhatt
  • 3,147
  • 19
  • 21