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
4 Answers 4
Don't use
stop(), useinterrupt().If you obey point 1, in
Class2you can use:
public void run() {
if(Thread.currentThread().isInterrupted())
//somebody interrupted me, ouch!
}
1 Comment
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.
- 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.
- 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).
2 Comments
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.
Comments
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?
Thread.stop? They are serious.