Thanks for all the answers.
I have finally found another solution. This solution uses interrupt()
and a loop controled by ! Thread.interrupted(). I wonder why this
solution is not always used (even when the threads are not waiting)
instead of the solution given by Sun that uses a variable that is set to
null to stop a thread. Someone can explain it to me?
Here is my solution :
public class Waiter3 implements Runnable {
public void run() {
Thread thisThread = Thread.currentThread();
int i = 0;
// Just to see the thread working
System.out.println(thisThread.getName() + i++);
while (! Thread.interrupted()) {
try {
Thread.sleep(1300);
}
catch(InterruptedException e) {
thisThread.interrupt();
}
System.out.println(thisThread.getName() + i++);
}
}
}
class Main3 {
public static void main(String[] args) throws InterruptedException {
Waiter3 waiter = new Waiter3();
Thread t1 = new Thread(waiter, "t1");
Thread t2 = new Thread(waiter, "t2");
t1.start();
t2.start();
// Sleep a little
Thread.sleep(3000);
// Stop thread t1, but not t2
System.out.println("Stop t1");
t1.interrupt();
Thread.sleep(15000);
System.out.println("Stop t2");
t2.interrupt();
}
}
Richard
William said:
xarax said:
Hello,
I have several threads created with a single Runnable :
Runnable runnable = new ... ;
for (int i = 0; i < t.length; i++) {
t = new Thread(runnable);
t.start();
}
How can I stop one of these threads (for example t[3].stop()) without
stopping the other ones, and without using stop which is deprecated ?
The example given by Sun to replace stop uses a variable but it does
not
work here because all the threads share the same Runnable.
Thanks in advance for your answers.
Richard
Using the same Runnable instance for multiple
threads is a design error. Rethink your design.
But in some conditions, it is an easy way to share data between
several threads. Anyway, I was wondering if there is a simple solution
to my problem. Can you tell me one?
Give each Thread a different name.
new Thread( runnable, "T" + i );
then use
Thread.currentThread().getName()
to see if the current thread is the one you want to stop.