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 example
Lockdown lockk = new Lockdown();
new Thread(lockk).start(); //thread1
new Thread(lockk).start(); //thread2
would 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 like
Lockdown lock1 = new Lockdown();
Lockdown lock2 = new Lockdown();
new Thread(lock1).start(); //thread1
new Thread(lock2).start(); //thread2
Output:
thread1 on lock1 print -> 6a
thread2 on lock2 print -> 7a
thread1 on lock1 print -> 6b
thread2 on lock2 print -> 7b
But it can also be:
thread1 on lock1 print -> 6a
thread1 on lock1 print -> 6b
thread2 on lock2 print -> 7a
thread2 on lock2 print -> 7b
So you can get 2 different results.