Search code examples
javasleepsynchronize

sleep() method behavior in synchronize block


class ThreadRunnable implements Runnable{
  synchronized public void run(){       
    System.out.println("In Runnable implemented class");

    try {
        Thread.sleep(60000);
        System.out.println("sleeping over");
        System.out.println(System.currentTimeMillis());
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}

public class Sample {
    public static void main(String [] args){
        ThreadRunnable tr = new ThreadRunnable();

        Thread t1 = new Thread(tr);

        Thread t2 = new Thread(new ThreadRunnable());

        t1.start();
        t2.start();
    }
}

As its in synchronize method, t2 thread should print the SOP after t1, but both the threads print the SOP simultaneously. Can anyone tell me why?


Solution

  • A synchronized method implicitly synchronizes on this. In your case the instance of ThreadRunnable.

    But each thread has its own instance so they use two different monitors.

    You have several options to solve your issue such as:

    • use a private static final Object lock = new Object(); as a monitor with a synchronized block.
    • or more simply Thread t2 = new Thread(tr);