is System.out.printf() statement asynchronous?

后端 未结 3 1359
名媛妹妹
名媛妹妹 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.

提交回复
热议问题