Reputation: 5
I have a Thread worker class Java, which is initiated several times (Lets say 10 instances). Now I want to stop these running threads one by one in the order they a created (First in first). All these thread objects are stored in an ArrayList. Could anyone help.
Thanks in advance Lee
Upvotes: 0
Views: 102
Reputation: 68975
Thread.join()
method is used for the same purpose. Docs here.
Lets say tou have Thread T1, T2 and T3.
To finish T3 before T2 and t2 before T1 you need to call T2.join() from T1 and T3.join() from T2. You can do something like below-
public class ThreadSync extends Thread {
Thread waitForThread;
public void setWaitForThread(Thread waitForThread) {
this.waitForThread = waitForThread;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " Thread Started");
if(waitForThread != null)
waitForThread.join();
System.out.println(Thread.currentThread().getName() + " Thread Terminating");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
Thread t1 = new ThreadSync();
t1.setName("T1");
Thread t2 = new ThreadSync();
t2.setName("T2");
Thread t3 = new ThreadSync();
t3.setName("T3");
((ThreadSync)t3).setWaitForThread(t2);
((ThreadSync)t2).setWaitForThread(t1);
t1.start();
t2.start();
t3.start();
}
}
Output is
T1 Thread Started
T3 Thread Started
T2 Thread Started
T1 Thread Terminating
T2 Thread Terminating
T3 Thread Terminating
Upvotes: 1
Reputation: 11392
In most cases, if I manage my own threads, I have some kind of flag (e.g. a volatile boolean or AtomicBoolean) that is checked on every run by a thread. E.g.
private volatile stop = false;
void stop(){
stop = true;
}
class Worker implements Runnable{
public void run(){
while(!stop){
... your logic
}
}
}
You can interrupted your threads if your threads are potentially blocking for something and you need to let them break free:
void stop(){
stop = true;
for(Thread thread: threads){
thread.interrupt();
}
}
Upvotes: 0
Reputation: 84
MyThread[] arr = new Thread[10];
for(int i = 0; i < arr.length; i++) {
arr[i] = new MyThread();
arr[i].start();
}
for(int i = 0; i < arr.length; i++) {
arr[i].join();
}
What this code does is useless (implement yiur own usage). join()
waits for the thread to die correctly (reach end of run()
). If you want to forcely kill a thread, use stop()
, but it is deprecated and unsafe.
Upvotes: 0