Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization problem

  public class PingPong implements Runnable {
      synchronized void hit(long n) {
          for (int i = 1; i < 3; i++)
              System.out.print(n + "-" + i + " ");
      }
      public static void main(String[] args) {
          new Thread(new PingPong()).start();
          new Thread(new PingPong()).start();
      }
      public void run() {
          hit(Thread.currentThread().getId());
      }
  }

The above code gives me output 8-1 9-1 8-2 9-2
But as the function is synchronized it should give output 8-1 8-2 9-1 9-2 or 9-1 9-2 8-1 8-2
Can anyone explain please?

like image 534
Android Killer Avatar asked Dec 13 '22 09:12

Android Killer


2 Answers

'synchronized' on a method synchronizes all accesses of that method on a particular object.

So if you have 1 PingPong object no 2 threads will simultaneously enter its hit method, but with 2 objects one thread can enter the hit method of one of the objects while another thread runs the hit object of the other.

This makes sense because you usually use synchronized to ensure undisturbed access to stuff local to the current object. If your object represents some external entity to which threads sometimes need undisturbed access, make your object a singleton.

like image 66
Arnout Engelen Avatar answered Dec 28 '22 23:12

Arnout Engelen


To get the behaviour you want, try making the following change:

 public class PingPong implements Runnable {
      synchronized void hit(long n) {
          for (int i = 1; i < 3; i++)
              System.out.print(n + "-" + i + " ");
      }
      public static void main(String[] args) {
          PingPong p = new PingPong();
          new Thread(p).start();
          new Thread(p).start();
      }
      public void run() {
          hit(Thread.currentThread().getId());
      }
  }

With only a single instance of PingPong, the synchronized modifier on hit() will prevent one thread from interrupting the other, and your output will be either X-1 X-2 Y-1 Y-2 or visa-versa.

like image 37
dlev Avatar answered Dec 29 '22 00:12

dlev