Best way to stop Thread

Hello

As per articles and forum discussions the thread has been stopped

3 different way.

1.Runnable State

private volatile Thread temp;

public void stop() {

temp = null;

}

2.Non - Runnable State

private volatile Thread temp;

public void stop() {

Thread tempA = temp;

temp = null;

if (tempA != null) {

tempA.interrupt();

}

}

3.

volatile boolean cancelled = false;

void cancel() { cancelled = true; }

Please let me know what is the exact scenario.

Regards

[588 byte] By [kr_07a] at [2007-11-27 3:09:46]
# 1

> 1.Runnable State

>

>private volatile Thread temp;

> public void stop() {

> temp = null;

>}

That doesn't stop the thread.

> 2.Non - Runnable State

>

> private volatile Thread temp;

>

> public void stop() {

> Thread tempA = temp;

> temp = null;

> if (tempA != null) {

>tempA.interrupt();

>}

That doesn't stop the thread. Setting thread references to null doesn't stop threads. The interrupt() call sets the thread's interrupt status, and interrupts wait() and join() and a few other methods such as NIO methods, but it doesn't stop a thread either.

> 3.

>volatile boolean cancelled = false;

>

>void cancel() { cancelled = true; }

And finally that doesn't stop a thread either.

The only legitimate way to stop a thread is (a) to interrupt it and (b) to have it watch out for the interrupt at regular intervals, via Thread.isInterrupted(), and having the thread exit when it sees the interrupt.

There is no legitimate way to stop a thread without its active cooperation.

ejpa at 2007-7-12 3:58:57 > top of Java-index,Core,Core APIs...
# 2
Thanks ejb
kr_07a at 2007-7-12 3:58:57 > top of Java-index,Core,Core APIs...