views:

469

answers:

4

I am calling two threads from a main thread, call them thread 1 and thread 2. When thread 1 stops, I want to stop or kill thread 2 also. How can I do this?There is a change in actual output what i want.That is There is a main class which is also thread.From main class i am calling thread1 and thread2.I am giving an input to thread1 from main class but when this input is getting changed i want to kill the running thread1 and start it once again with another input.The second thread,thread2 will run with the output given by the thread1.So eventually when the first thread is killed the second will be running but will give an output only if t6here is an input for that thread.

+12  A: 

Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).

You might also be interested in setting the second thread as a daemon thread, which means that in case all other threads in the VM have finished then the process will exit.

abyx
+2  A: 

According to these instructions, it's best to use flag variables to tell the other thread to stop its work cleanly.

ammoQ
Thanx a lot for the suggestion but cud u help me in properly specifying it.
Raji
+4  A: 

See this Java Specialist article on how to shut down threads cleanly.

Briefly, the article recommends Thread.interrupt() plus the appropriate InterruptedException handling in the thread code. That's an interesting discussion in itself, and something I rarely see done correctly.

Brian Agnew
That article is a great read and recommended to anyone that doesn't have enough time to read Doug Lea's Concurrent Programming in Java
abyx
+1  A: 

In the run() method of your thread, check an attribute that is set through an accessor method like shutdown() when you want to stop the thread, use that value to end the while loop. For example:

boolean stopping = false;

Thread currentThread = null;

public void run() {

    currentThread = Thread.currentThread();

    while (!isStopping()) {

        // do something, sleep a while
    }
}

public synchronized void shutdown() {

    stopping = true;

    currentThread.notifyAll();
}

public synchronized boolean isStopping() {

    return stopping;
}
rsp
Your code has a race condition and your use of synchronization is poor. Its much better to simply check the interrupted status of the current thread or if you MUST use some sort of sentinel, at least make it atomic.
Kevin
@Kevin, you must've missed the *For example* bit, this code obviously is only meant to show the structure of a solution - not to be used as is.
rsp
@rsp: If you post examples, preferrably make them good examples. If people already knew to distinguish good from bad examples, they would not have to ask here.
Daniel Schneller