Hi Robbie. I agree with Anupam. Anupam, you beat me to the answer, but here's my take on the question anyway:
As the program stands, in the
main method, the following happens:
- The
sa array is locked by the
main thread.
- the thread
t1 is created and started by the
main thread. As long as the
main thread has a lock on the
sa array, the body of the
run method in class
At(which will be invoked as a result of starting the
t1 thread) cannot proceed (i.e. cannot enter the
synchronized(sa) block) until the
main thread releases its lock on
sa.
- Before the
main thread releases its lock on
sa (i.e. before it exits its synchronized block), the
main thread changes the contents of
sa (to "A", "B", "C").
- Once the
main thread releases its lock on
sa the
t1 thread will no longer be blocked and will be free to aquire the lock on
sa. The
t1 thread will then print the new/changed values (i.e. "A", "B", "C") of
sa.
If you remove the
synchronized statement from the
main method, then the output of the program is theoretically unpredicatable: the
main thread could change the values of
sa (to "A", "B", "C") before the
t1 thread starts,
OR t1 could run immediately after the call to
t1.start(), aquire the lock on
sa, and print "XYZ".
[ May 18, 2003: Message edited by: Rory French ]