I am printing information to test Threads using Reentrant locks. I am creating fair locks using statement new ReentrantLock(true).
In one of the object method where I a
I am creating 10 threads and all threads should executing same statement 3 times where this console print statement is executed. however, I am not getting output where I see every thread showing the print in same sequence. e.g.
A specific sequence of output is hard (and unnecessary) to get with threads. System.out.printf(...)
is a synchronized operation so the output will never overlap each other, but the order of the output lines is unpredictable because of the race conditions inherent in running multiple threads at one time. In terms of asynchronous (which has nothing to do with thread synchronization), by default System.out
has auto-flush enabled, so all writes to a PrintStream
get flushed on every write.
Specific order of output of threaded applications is a FAQ. See my answer here: unwanted output in multithreading
To quote from the answer, the order that threads run cannot be predicted due to hardware, race-conditions, time-slicing randomness, and other factors.