As long as you don't change the OutputStream
via System.setOut
it is thread safe.
Though it is thread safe you can have many threads writing to System.out
such that
Thread-1
System.out.println("A");
System.out.println("B");
System.out.println("C");
Thread-2
System.out.println("1");
System.out.println("2");
System.out.println("3");
can read
1
2
A
3
B
C
among other combinations.
So to answer your question:
When you write to System.out
– it acquires a lock on the OutputStream
instance - it will then write to the buffer and immediately flush.
Once it releases the lock, the OutputStream
is flushed and written to. There would not be an instance where you would have different strings joined like 1A 2B
.
Edit to answer your edit:
That would not happen with System.out.println
. Since the PrintStream
synchronizes the entire function, it will fill the buffer and then flush it atomically. Any new thread coming in will now have a fresh buffer to work with.