简体   繁体   中英

volatile keyword can't stop loop in java

public class VolatileOne {
    private static boolean ready ;
    private static int number ;

    private static class ReaderThread extends Thread{
        @Override
        public void run() {
            while (!ready){
                Thread.yield();
            }
            System.out.print(number);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().run();
        ready = true;
        number = 50;
    }
}

After running this code, the program does not stop, which is obvious because the thread backs up variables ready into the memory of its own process. When I use volatile keyword to modify read

private volatile static boolean ready ;

the read variable will not be copied into process memory at this time. But the program can't stop. What's the reason? Is it related to the static keyword?

If you want the program to output 50 and return, what should you do?

  1. You need call start to execute the code in another thread. Check this for the difference between run and start .

  2. Call join to wait the ReaderThread finish.

  3. volatile keyword can build a happens-before relationship between the write and the read thread, you can put number = 50; before ready = true; , which makes sure the reader will notice number is 50 when it notice ready is true .

Example:

Thread reader = new ReaderThread();
reader.start();
number = 50;
ready = true;
reader.join();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM