Relationship between Threads and println() statements

前端 未结 2 1134
别跟我提以往
别跟我提以往 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: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.

提交回复
热议问题