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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With