Why is the answer to this letter b? (question and answer below) I understand 7a 7b 8a 8b, since the method is synchronized hence only one thread could execute at a time, but why is 6a 7a 6b 7b acceptable as well? shouldn't the second thread wait for the first thread to finish with the method?
public class Lockdown implements Runnable {
public static void main(String[] args) {
new Thread(new Lockdown()).start();
new Thread(new Lockdown()).start();
}
public void run() { locked(Thread.currentThread().getId()); }
synchronized void locked(long id) {
System.out.print(id + "a ");
System.out.print(id + "b ");
}
}
b) Set 7a 7b 8a 8b and set 6a 7a 6b 7b are both possible. (*)
That is correct because there are two
Lockdown
objects and a thread for each one. For examplewould cause the threads to wait the first to finish execution. So the result will always be
7a 7b 8a 8b
, or something like that. Synchronized methods make threads to wait only if the threads are running on the same object.But with the threads operating on different objects it may also output
6a 7a 6b 7b
. Your example is likeOutput:
But it can also be:
So you can get 2 different results.