How to stop each thread at a time in multiple threads in Java?
<p>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.</p>

<p>I got the code from <a href="http://www.java67.com/2015/07/how-to-stop-thread-in-java-example.html#ixzz4QmDGuiK4" rel="nofollow noreferrer">How to stop a thread in Java? Example</a>
and it works well for one thread.</p>

<p>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.</p>

<p>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?</p>

<pre><code>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 &lt; pool.length; i++) {
            pool[i] = new Server();
            pool[i].start();
        }

        for(int i = 0; i &lt; 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() {
      ...
    }
}
</code></pre>