6

Well, I met an amazing question...

public class Test {
    private boolean[] state = new boolean[]{false, false};

    public void createThread() {
        Thread th1  = new Thread(() -> {
            try {
                System.out.println("1");
                Thread.sleep(2000);
                state[0]=true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread th2 = new Thread(() -> {
            try {
                System.out.println("2");
                Thread.sleep(2000);
                state[1] = true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
        th1.start();
        th2.start();
    }
    public static void main(String args[]) throws InterruptedException {
        Test test = new Test();
        test.createThread();
        while (true) {
//            Thread.sleep(1);
            if (test.state[0] && test.state[1]) {
                System.out.println("stopped");
                break;
            }
        }
    }
}

If i don't add the Thread.sleep(1) statement or some code else, "stop" wont't be printed. If i add something in while, "stop" will be printed. How would this happen? Every answer is helpful.

1 Answer 1

8

The answer might be simple but lies in the detail.

Your array which keeps the states is not marked as volatile and therefore the if-statement in your while loop is not forced to use the most updated value.

Simply changing

private boolean[] state = new boolean[] { false, false };

to

private volatile boolean[] state = new boolean[] { false, false };

would to the trick.

Sign up to request clarification or add additional context in comments.

2 Comments

Does that mean that without volitale the while(true) loop will see the cached state for ever?
@oreh depends on the rest of the program (as OP mentioned that it works by adding Thread.sleep(1)). The only thing I can say for sure is that the volatile keyword forces each thread to compare their chaced value against the "most recent" value in the main memory. For further information please read the tutorial linked in my post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.