Search code examples
javamultithreadingvolatile

One thread not stopping other . Even with volatile variable


I am test a scenario to use volatile variable to stop one running thread from another. I wonder why its not working. Where is the problem? My code is:

public class StoppableTask extends Thread {
    private  volatile boolean pleaseStop;

    public void run() {
       System.out.println("Running..");
       while (!pleaseStop) {
           System.out.println("Working...");
       }
    }
    public void tellMeToStop() {
        pleaseStop = true;
    }
}

public class Stopper extends Thread {
    StoppableTask t ; 

    public Stopper(StoppableTask t){
        this.t=t;
    }
    public void run(){
        System.out.println("Ok..running too..");
        try {
            System.out.println("Waiting..");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.tellMeToStop();
        System.out.println("Done Waiting..");
    }

    public class QuickTest{

        public static void main(String[] args) {
        StoppableTask t = new StoppableTask();
        Stopper s = new Stopper(t);
        t.start();
        s.start();

    }
 }

Solution

  • I suspect that your program is printing so much output to the terminal that it is blocking waiting for the output to be displayed. It looks like it is not stopping but really it will. You just need to wait... for a long time...

    You should put a Thread.sleep(100); inside of of the while() spin loop in StoppableTask.run() to slow down that output. Another way to do it is to remove the System.out and just increment a counter or something.

    I just tried it and your program finishes in 5 seconds as expected:

    public void run() {
        System.out.println("Running..");
        while (!pleaseStop) {
            // System.out.println("Working...");
        }
        System.out.println("Stopped task Done");
    }