Hi ranchers,
E and F are correct
A doesn't do, because there is no synchronization at all.
B doesn't do either. with a synchronized run method, you synchronze on
this, i.e. the tread. With the two threads, each of them has an independent lock on itself.
C does not compile as you cannot override a nonstatic with a static method.
D doesn't do, because it's just the same as B.
E works fine. You synchronize on the class literal, that is shared by all objects of this class. Sync works. Each of the two
thread objects has first to aquire a lock on that common object before it can run the synchronized block.
F works fine also. You synchronize on the out object, the output stream. So each thread must wait for the other to give up its lock to the output stream before it can print anything.
G does not compile. Only classes have this class literal, but not objects thereof. If it said synchronized(System.class) it would work, like with answer E.
By the way, you can
test this all for yourself.
But
you should put a yield(); between the two outputs of the write() method. Otherwise you may not see a difference between sync and no-sync. Also it would be nice to print more than just two letters, eg try this:
Yours,
Bu.