Matheus Souza wrote:It says that the answer is: 000000
That is correct.
Matheus Souza wrote:Can anyone explain to me what happened?
What
exactly didn't you understand? Is it why 6 numbers are printed? Or is it why 0 is printed every time? Or both?
6 numbers were printed because, after execution of 1
thread (just
one thread. not
first or
second - because we cannot guarantee which thread will execute first), length of s would be 1. After execution of 2 threads, length of s would be 2 and after execution of 3 threads length would be 3. Further, we are printing s for 3 times, hence, we get 1+2+3=6 numbers. This modification of s is thread safe because of synchronization(line 20)
Now, what happens to those numbers we passed during object creation (2,1 and 0)? Well, x is volatile. So, every time, a thread would refer copy from main memory (and not thread's local memory), so it will take 0 every time.
I hope this helps.