user999379
user999379

Reputation: 411

java threads notify

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

Answers (4)

Jatin
Jatin

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.

  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).

Upvotes: 2

Ravi Bhatt
Ravi Bhatt

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

John B
John B

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

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

  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!
}

Upvotes: 5

Related Questions