is System.out.printf() statement asynchronous?

╄→гoц情女王★ 提交于 2019-12-02 03:07:07
Gray

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:

  • 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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!