I'm trying to make use of the keyword "synchronized" but the results are not correct. I'm not able to figure out why call to third object is given before the second one.
Expected Output:
hello
synchronized
world
Output - What i'm getting
hello
world
synchronized
Below is the code I am using:
class Callme{
synchronized void call(String msg){
System.out.print("["+msg);
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}
System.out.println("]");
}
}
class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s){
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run(){
target.call(msg);
}
}
class Synch{
public static void main(String[] args){
Callme target=new Callme();
Caller c1=new Caller(target,"hello");
Caller c2=new Caller(target,"Synchronized");
Caller c3=new Caller(target,"world");
try{
System.out.println("Waiting for the threads to end");
c1.t.join();
c2.t.join();
c3.t.join();
}catch(InterruptedException ie){}
}
}
You're starting three threads. Each of those will call call
on the same Callme
, so only one thread will be executing call
at a time... but that doesn't mean that the threads will execute in the order that you started them.
Imagine you start a running race, and half way round the track you have a gate that only one person can pass through at a time. You start 10 runners at roughly the same time - why would you expect the runners to enter the gate in exactly the same order that you started them?
Basically, synchronization provides exclusivity - it doesn't specify ordering.
See more on this question at Stackoverflow