0

This code end up with different results if I change the parameter of sleep(), and here is some sample outcomes:

1.sleep(1l), the thread will always terminate automaticlly, the "Stoped" statement will always be printed, and the icon of "Terminate" in Eclipse will be grey too. (seems working perfectly huh?)

2.sleep(1000l), here comes the problem, if main thread sleeps for 1 second, the Thread v will never terminated automaticlly, the "Stoped" will not be printed, and the icon of "Terminate" is red, which means there is still some thread running.

I know it could be solved if I add "volitale" for the parameter "isRunning", but I wonder why and how does the sleep() statement affect the outcome?

PS:I'm a newbie for both java and english, so I apologize for any possible discomforts due to this question.

public class VolitaleTest {

    public static void main(String[] args) throws InterruptedException {

        Vo v = new Vo();
        new Thread(v).start();
        Thread.sleep(1000l);
        v.setRunning(false);
        System.out.println(v.i);
    }
}

class Vo implements Runnable {

    private boolean isRunning = true;
    int i = 0;

    public void run() {
        while (isRunning) {
            i++;
            // System.out.println("Running");
            /*
             * Once you add this statement, you will always be able to terminate
             * the program automatically, no matter how long the thread sleeps.
             */
        }
        System.out.println("Stoped.");
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }
}

1 Answers1

1

volatile makes it possible for what one thread wrote up to and including writing to the volatile variable to be visible to another thread starting from when it reads that variable. If the variable is not volatile then that happens-before memory relationship is not guaranteed.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10