Java problems encountered, seeking answers

Topic One: Visibility

public class Demo {

    private static Boolean flag = true;


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

        new Thread (() -> {
            System.out.println ("测试线程启动");
            while (flag) {
                
            }
            System.out.println ("测试线程结束");
        }).start ();
        TimeUnit.SECONDS.sleep (1);
        flag = false;
        Runtime.getRuntime ().addShutdownHook (new Thread (() -> {
            System.out.println (Thread.currentThread ().getName () + "钩子线程结束,表示程序退出");
        }));


    }

}

       As follows: main method to start a thread. Inside a while loop, when the main thread is a shared variable is set to false, in order to terminate the thread of the test cycle so that it terminates, so inject a hook thread to determine whether the program terminates, but the visibility is so unkillable , so only one line console print the following information: test thread starts.

        So the question is, will change the code a little bit, adding a lock in a while loop, why do shared variables can be met? Question: We all know that really is locked so that the object can be locked so that other threads can be seen, but I have here is just a string lock it, so why have it?

public class Demo {

    private static Boolean flag = true;


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

        new Thread (() -> {
            System.out.println ("测试线程启动");
            while (flag) {
                synchronized (""){

                }
            }
            System.out.println ("测试线程结束");
        }).start ();
        TimeUnit.SECONDS.sleep (1);
        flag = false;
        Runtime.getRuntime ().addShutdownHook (new Thread (() -> {
            System.out.println (Thread.currentThread ().getName () + "钩子线程结束,表示程序退出");
        }));

    }

}
测试线程启动
测试线程结束
Thread-1钩子线程结束,表示程序退出

 

 

 

Published 73 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40826106/article/details/102754378