Search code examples
javamultithreadingsynchronizationexecution

Thread synchronization and execution order


So imagine there's a class A that implements Runnable like so:

class A implements Runnable {
    C c;
    Thread t;

    public A(C c){
        this.c = c;
        t = new Thread(this);
    }

    public void start(){
        t.start();
    }

    public void run(){
        for (int i = 0; i < 5; i++){
            c.doIt();
        }
    }
}

Class C just contains a synchronized method that prints current thread details by character, like this:

class C {
    synchronized void doIt(){
        String s = Thread.currentThread().toString();

        for (int i = 0; i < s.length(); i++) {
            System.out.print(s.charAt(i));
        }

        System.out.println();
    }
}

If I create 2 threads in my main method, while using a shared object c of class C, shouldn't I receive a random order of thread execution, since only the doIt method is synchronized? The way I imagined that, is that t2 thread would be able to receive control after an iteration of doIt() is done by t1. It seems that the lock is acquired by t1 until the whole loop of the thread has finished it's work. So my question is - does the synchronization mean that the thread must also finish before the other one kicks in (not only the synchronization of doIt())?


Solution

  • Synchronized Instance Methods Here is a synchronized instance method:

      public synchronized void add(int value){
          this.count += value;
      }
    

    Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized.

    A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance. (c) http://tutorials.jenkov.com/java-concurrency/synchronized.html

    So that means, in your case, that another thread could have access to the method when first thread finish it's first call of doIt(), but this is not guaranteed.