简体   繁体   中英

java synchronized Thread clarification

The answer for this program will have to be "Changing done" after 5 secs, but I get "Changing done" and "DONE". I do not have the getDone method as synchronized. Any ideas what am I doing for the thread to finish processing.

public class Main {
    private static boolean done = false;
    private static int count;

    public static void main(String[] args)throws InterruptedException {
        new Thread(() -> {
            while (!getDone()) {
                count = count + 1;
            }
            System.out.println("DONE!!!!");
        }).start();
            Thread.sleep(5000);
        System.out.println("Changing done");
        synchronized (Main.class) {
            done = true;
        }
    }

    public static boolean getDone() {
        return done;
    }
}

If you don't synchronize access to done properly, it means your code may fail, ie the thread may not see the updated value.

It does not mean the value is guaranteed not visible unless synchronizing correctly. So, in many cases the write to done is still visible (the fact that broken code still works in many cases makes concurrent programming harder). It is just not guaranteed to work in every case.

I do not have the getDone method as synchronized. Any ideas what am I doing for the thread to finish processing.

As you mention, there is no explicit memory synchronization between the done as seen by your spinning thread and the main thread. Although the main thread crosses a write memory barrier when exiting the synchronized block, there is no explicit read memory barrier crossed by the spinning thread.

However, there are many ways for a thread to see updated information. If the operating system swaps the thread out of its running processor, the cached memory may be lost so when the thread gets swapped back it, it will request done from central memory and will see the update.

Also, although your example code doesn't show it, if you make calls to other synchronized methods (such as System.out.println() ) or cross other memory barriers (accessing another volatile field), then this will also cause done to be updated.

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