Dear all,
I have a very simple exercise. Given a StringBuffer str with the initial value "A". Three threads will print value of str for 3 times, then add "+" after str, then print it 3 times again. I have to synchronize this process so that three threads with do this sequentially. And here is my code:
The result is bizzare, three threads execute the doit() method in parallel:
However, if I make a little change with the doit() method declaration by removing the synchronized key
word and put it inside the method like that:
Then everything is fine, I got the result as expected, only one
thread can execute doit() at one moment :
Can any one help me to understand? I use to think that if I put synchronized in the method doit() then only one thread can execute it at one moment?