Reputation: 1541
What I need to do is creating multiple threads ( eg. 3 threads in example code) and each thread is performing its own computation. After each thread finishes its computation, the corresponding thread should be stopped.
I got the code from How to stop a thread in Java? Example and it works well for one thread.
However, if I modify this code for multiple threads, then each thread doesn't stop and keeps running. Which means although a thread finishes its doSomeComputation(), it computes again from the beginning instead of stopping it.
I've been googling and searching this website, and tried this and that ( using interrupt, Thread.stop() and so on ). But couldn't find a way I wanted. How to stop each thread, whenever it's own doSomeComputation() is done in each thread?
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.currentThread;
public class ThreadStopDemo {
public static void main(String args[]) throws InterruptedException {
ThreadStopDemo tsd = new ThreadStopDemo();
tsd.test2(); // NOT stop
// tsd.test1(); // stop
}
// this works well.
void test1() throws InterruptedException {
Server myServer = new Server();
Thread t1 = new Thread(myServer, "T1");
t1.start();
System.out.println(currentThread().getName() + " is stopping Server thread");
myServer.stopThread();
TimeUnit.MILLISECONDS.sleep(200);
System.out.println(currentThread().getName() + " is finished now");
}
// this doesn't stop and keeps running.
void test2() throws InterruptedException {
Server[] pool = new Server[3];
for(int i = 0; i < pool.length; i++) {
pool[i] = new Server();
pool[i].start();
}
for(int i = 0; i < pool.length; i++) {
System.out.println(currentThread().getName() + " is stopping Server thread");
pool[i].stopThread();
TimeUnit.MILLISECONDS.sleep(200);
System.out.println(currentThread().getName() + " is finished now\n");
}
}
}
class Server extends Thread {
private volatile boolean exit = false;
public void run() {
while (!exit) {
System.out.println(currentThread().getName() + " Server is running.....");
doSomeComputation();
}
System.out.println(currentThread().getName() + " Server is stopped....");
}
public void stopThread() {
exit = true;
}
void doSomeComputation() {
...
}
}
Upvotes: 0
Views: 89
Reputation: 560
The best way to wait for multiple threads is to use ExecutorService.submit(), then call Future.get() to wait for the jobs to complete.
Upvotes: 1