0

The code below is that I try to stop a thread I created without using stop(). However, The thread seems like it would executed once more after it be stopped. I wonder why this happened? Plus: If I change the iteration from 100 to 10, it works without any problems. Can anyone help me with this problem? Thanks in advance!

  public class TerminateThread implements Runnable{
    private boolean flag = true;
    public TerminateThread(String name) {
        this.name = name;
    }
    private String name;
    public void run() {
        int i = 0;
        while(flag) {
            System.out.println(name+"--->"+i++);
        }

    }
    public void Terminate() {
        this.flag = false;
    }

    public static void main(String[] args) {
        TerminateThread tt = new TerminateThread("Thread");
        new Thread(tt).start();
        for (int i = 0; i <= 100; i++) {
            if (i == 88) {
                tt.Terminate();
                System.out.println("Thread terminated!!!");
            }
            System.out.println("main--->" + i);
        }

    }

}

The outcome is : enter image description here

Nick WEI
  • 33
  • 5

1 Answers1

5

Well the thing is, your code doesn't terminate the thread, it simply makes it finish its work at the next iteration.

What could be happening is the flag variable isn't being instantly updated to all threads when changed, and you are setting it with the main thread. To remedy this, declare flag as volatile.

private volatile boolean flag = true;

More Info: What is the volatile keyword useful for