posted 13 years ago
Yes. When two threads starts at line 18 and 19, they are two pieces of light weighted processes running by JVM . The operating system will do its own processing. For example, in round robbin fashion. Maybe, the operating system let thread 1 run for 1 second, and thred 2 run for 1 second and etc. Maybe , some operating systems let thread 1 run first and then thread 2. Maybe, some operating systems let thread 1 run for 2 second, pause thread 1, let thread 2 run for 3 seconds, pause thread 1, let thread 1 run for another 1 second and etc. We never know how operating system handles the time slice of the thread.
Yes. Both Lucy and Fred execute the run method staring from x=0 to x=4 on their own. x is a local variable in run() method. Lucy has its own copy of x and Fred has its own copy of x. Remember in KB's book, we don't need to synchronize any local variable inside a method because the thread will have its own local variables which won't affect each other.
But both of them are sharing the same AccountDanger instance in this case. Also, makeWithdrawal is not synchronized. Therefore, both of them will withdraw money from the same AccountDanger instance. This is a typical violation of mutual exclusion in operating system.
Correct me if I am wrong in anything.