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.
System.out
is a buffered stream. This mean that it doesn't fill the console synchroneously.
While the printf()
call is synchrone, the console output is not.
You can either:
System.out.flush();
,println()
which auto-flushes the stream,System.err
which is not AFAIK buffered. Not sure about the last one...
Note that your threads are executed concurrently (if you use .start()
) Which means you cannot expect precisely any execution order without synchronization elements.
Although it is hard to answer this question without seeing the code starting the threads, this does not seem to have anything to do with the behavior of System.out.printf(). The threads you are starting are waking up and sleeping independently from each other, so the order of the lines printed among the threads is dependent on the JVM running the code. If you need the statements in order, but you want to do the work in parallel, a CyclicBarrier could be used to coordinate the print statements.