Frage

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. (*)

War es hilfreich?

Lösung

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.

Andere Tipps

Printing or logging is not the part of synchronization. Read this section completely : It is similar to question : Inconsistency in output for Producer Consumer relationship program in Java

Did you try running the code?

I did and I got results as

9a 9b 10a 10b

Second time I got

9a 10a 10b 9b

Which means that the threads acquire and release locks arbitrarily. You cannot predict the execution sequence until it really happens.

Note that synchronized keyword guarantees that only one thread access the code block at a time.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top