Relationship between Threads and println() statements

前端 未结 2 1058
别跟我提以往
别跟我提以往 2020-12-20 15:46

I was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads. And I noticed that in almost all the cases I tested, if inside

相关标签:
2条回答
  • 2020-12-20 16:48

    This behaviour is implementation specific. In OpenJDK, println's body is synchronized altough the API does not state that it is.

    0 讨论(0)
  • 2020-12-20 16:49

    PrintWriter is synchronized

    public void println(String x) {
        synchronized(this) {
            this.print(x);
            this.newLine();
        }
    }
    

    Two sequential calls of System.out.println() in main thread and in second thread create a synchronization order between two threads. That means that all actions (in your case it is variable update), that happened in main thread before releasing a monitor (exiting synchronized method) will be seen by the code, executed in second thread after it acquires a monitor (enter synchronized method).

    In simple words, yes, calling System.out.println() makes this synchronization.

    0 讨论(0)
提交回复
热议问题