Why does StringBuilder access appear to be synchronized?

This question already has an answer here:

  • Difference between StringBuilder and StringBuffer 31 answers

  • You are using diferents instances of StringBuffers and StringBuilders per thread. To see the synchronization, you must use same instance of object in all threads ;-)


    A description of expected versus actual behavior would be helpful, but I'm guessing that you saw sequential output from each thread, but expected to see output interleaved from different threads.

    Thread scheduling depends on the system. There is no guarantee that threads will be scheduled fairly (with threads of equal priority getting "time slices," for example), or that threads will run concurrently, even on a multiprocessor system.

    Also, remember that System.out.println() is synchronized, and contention for intrinsic locks isn't guaranteed to be resolved fairly or immediately. So it's possible that one thread repeatedly acquires the lock on System.out , and other threads don't get a chance to print until that thread is finished. You can get "fair" locking (with a possible performance penalty) using a java.util.concurrent.ReentrantLock .

    Another possibility is that your system is so fast that one thread finishes before the next thread even tries to start running. More iterations would help detect that case.


    You should have used same instance of StringBuilder/StingBuffer for all thread. so that you can see synchronization.

    链接地址: http://www.djcxy.com/p/72346.html

    上一篇: StringBuffer和StringBuilder之间的区别

    下一篇: 为什么StringBuilder访问似乎是同步的?