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

1,187 阅读1分钟

源码

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()每次输出都会清除工作内存去同步主内存中的变量。