Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a simple java multithread

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.

like image 467
treeliked Avatar asked Jun 02 '18 09:06

treeliked


1 Answers

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.

like image 61
L.Spillner Avatar answered Sep 21 '22 01:09

L.Spillner