Locking on Integer object -- either first or redlight -- renders the desired result: each thread completes the 12 iterations before the next thread comes around.
On purpose, I avoided using a for-loop. I am trying to understand what "this" in synchronized (this) means. I do not understand why if I replace either object --- first or redlight --- with "this" and still keep the curly braces arond the same lines of code, I no longer get the desired result. What does "this" mean? I cannot find a case where I can use synchronize (this) effectively.
Graciela the behavior that you are seeing is due to the integer constant pool that java maintains. When an int is boxed into Integer, and its in the range of -128 to 127, then the Integer object is taken from that pool. This is defined in the JLS
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
So you have three instances of Letter2 class which all have the same instances of first and redlight. That's why synchronization works on them but not on this. Try to modify your code in one of the following manners
Both the above codes will work similar to this now i.e. the synchronization will not work...