StringBuffer and StringBuilder thread safety problem analysis

StringBuffer string variable (thread-safe in a multithreaded situation to ensure the safe operation of the thread)
the StringBuilder string variable (non-thread-safe run more quickly)

 

/ * Deal with thread-safety issues, we can change as a string of two to achieve, the first is the index of the string stored elements 
* and then continue to increase the value of Size in the single-threaded case if size is equal to 0 then add an element step is an element in position 0, then 1 = size
* to do so in a single thread is no problem
* but: if multiple threads -> thread elements in a position to 0 but at this thread B also assume snatch snatch CPU successful then this time a thread size of the increase has not been run to that step
* colleague, b thread at position 0 and put an element, which will be a thread back into the elements overwrite
* so: Let's look at the actual situation is that two elements are placed in position 0 but the actual element has only one, size is equal to 2 but this creates problems not thread-safe * /


see below an analysis of the

 

Guess you like

Origin www.cnblogs.com/LWF6869/p/12417062.html