is System.out.printf() statement asynchronous?

后端 未结 3 1356
名媛妹妹
名媛妹妹 2021-01-22 08:22

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

相关标签:
3条回答
  • 2021-01-22 09:07

    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.

    0 讨论(0)
  • 2021-01-22 09:16

    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:

    • flush() System.out by calling System.out.flush();,
    • use println() which auto-flushes the stream,
    • use 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.

    0 讨论(0)
  • 2021-01-22 09:16

    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.

    0 讨论(0)
提交回复
热议问题