System.out.println()对线程安全的影响

源码

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

public void println() {
	newLine();
}
private void newLine() {
	try {
		synchronized (this) {
			ensureOpen();
			textOut.newLine();
			textOut.flushBuffer();
			charOut.flushBuffer();
			if (autoFlush)
			out.flush();
		}
    }
    catch (InterruptedIOException x) {
      	Thread.currentThread().interrupt();
    }
    catch (IOException x) {
      	trouble = true;
    }
}

复制代码

输出时会加锁同步,如果是循环输出,那么JVM会进行锁优化——锁粗化,避免一个对象反复地加锁和解锁。

System.out.println()每次输出都会清除工作内存去同步主内存中的变量。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享