Influence of synchronized method on non synchronized method
StringBuilder is a thread unsafe class.
StringBuffer is thread safe because its methods are synchronized.
Today, I wrote a piece of code to test it: start 10 threads with a loop, call the append of StringBuffer (StringBuilder), and append 1 to 10.
The result is expected to be the same: the thread unsafe StringBuilder will miss some numbers,
@H_ 404_ 13@
All 10 numbers are appended to the thread safe StringBuffer:
@H_ 404_ 13@
At this time: if I operate the builder and buffer at the same time and call the append of the buffer first, the builder method is changed into a "synchronous" method because the buffer blocks the thread because the builder and buffer are in the same thread every time, and 10 numbers are also appended
@H_ 404_ 13@
The above article on the impact of synchronized methods on non synchronized methods is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.