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?
‘synchronized’ on a method synchronizes all accesses of that method on a particular object.
So if you have 1
PingPongobject no 2 threads will simultaneously enter itshitmethod, but with 2 objects one thread can enter thehitmethod of one of the objects while another thread runs thehitobject of the other.This makes sense because you usually use
synchronizedto 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.