Reputation: 411
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
Upvotes: 0
Views: 405
Reputation: 31724
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.
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).Upvotes: 2
Reputation: 3163
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?
Upvotes: 0
Reputation: 32949
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.
Upvotes: 0
Reputation: 340713
Don't use stop()
, use interrupt()
.
If you obey point 1, in Class2
you can use:
public void run() {
if(Thread.currentThread().isInterrupted())
//somebody interrupted me, ouch!
}
Upvotes: 5