Meaning of scanner isn't synchronized

半城伤御伤魂 提交于 2019-12-12 20:06:21

问题


I was going through the differences between scanner and BufferedReader in Java and one point which I could not understand was that said

Scanner is not synchronized while BufferedReader is.

Now can anyone please explain what it means?


回答1:


Literally, it means what it says. Key operations of the BufferedReader API are implemented using synchronized blocks, and the equivalent operations in Scanner are not.

This means that a BufferedReader can be "safely" shared between multiple threads1, whereas a Scanner cannot. A Scanner is inherently non-thread-safe, even if it wraps a thread-safe input source.


1 - Actually, this does not absolve you from thinking about threading. If you have multiple threads calling read(...) operations on the same BufferedReader without some form of coordination, then there is no way to know which thread will read which characters from the stream. By some definitions, that would make the usage non-thread-safe. The disposition of the characters to the right threads is usually important to the correctness of the application.



来源:https://stackoverflow.com/questions/36672989/meaning-of-scanner-isnt-synchronized

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