Click to See Complete Forum and Search --> : close thread from another thread


attilio
October 16th, 2005, 08:33 AM
hi guys,

My code runs a thread, then another one. If 1 thread recieves a specific command it needs to be able to close the other thread - stop it from processing anything.

Atm both the threads run a while(true) {
} statement.

If 1 thread recieves the command to stop the other then it flags, t[1].kill =1; where t[1] = the path to the other thread.

This thread, on the next data input checks if t[this.i].kill==1, if so runs the break; command and closes itself....


It works fine, but it has to recieve data to be closed, if data isn't recieved it wont check t[this.i].kill and wont break; to close

I want to know If I can close it from the other thread, ie instead of flagging a variable, t[1].kill = 1, it does something like t[1].close(); or something.....

any ideas appreciated thanks

wildfrog
October 16th, 2005, 09:15 AM
If a thread is blocked by a blocking sleep/wait/read/write operation you can call the Thread.interrupt() function to wake it up.

- petter

attilio
October 16th, 2005, 11:50 AM
thanks for the reply.

The thread is stopped waiting for a variable to be set. heres the code:


while(true) {



line = r.readLine();

if(line==null) {

break;


} else {

its waiting for the value of line to be set before it can continue.

Thus its halted until this happens. If another thread wants to close it it has to wait until this value is set before it will kill itself.

I have tried the interrupt() function, but it doesn't do anything....

attilio
October 16th, 2005, 01:02 PM
ok maybe i can make it easier to understand.

I need to exit the run() function within the thread before it dies out naturally.

the problem is its stopping for system i/o from the dataInputStream(); at

line = r.readLine();

Either, if it's prossible I need to set the r.readLine() value manually so it continues, or i need to kill the run() method in its tracks.

thanks for any help

Joe Nellis
October 16th, 2005, 02:04 PM
The stop method of thread management has been deprecated. The correct procedure for ending a thread is to let it run out. This means you need a conditional check in the while that is going to let you out of the loop. Bascially this means setting a variable that it checks.

// thread 1 run method
...
while( var ){
// do stuff
}

// thread 1 setVar method
public synchronized void setVar(boolean val){
var = val;
}

// thread 2, somewhere, decision to end thread 1;
thread1.setVar(true);

Also, if you are being blocked by readline from an input stream, you can check if the ready() method to check if there is input to read.

attilio
October 16th, 2005, 03:01 PM
ok thanks my friend, although in the end I used the inputStream.close(); to stop it, then followed with my exit code