I am currently learning Java, and I have reached the topic of Synchronization.
For some reasons, the code below (based on the code from The Complete Reference JAVA - Herbert Schildt 7th Edition, Pg no. 239-240) does not give the required output.
Code:
package package1;
class Call{
synchronized public void call(String msg){
System.out.print("[" + msg);
try{
Thread.sleep(100);
}catch (InterruptedException e){
System.out.println("Interrupted Exception Caught");
}
System.out.println("]");
}
}
class CallMe implements Runnable{
String msg;
Call target;
Thread t;
public CallMe(Call targ, String message){
target = targ;
msg = message;
t = new Thread(this);
t.start();
}
public void run(){
target.call(msg);
}
}
public class Synchronization {
public static void main(String[] args) {
Call target = new Call();
CallMe obj1 = new CallMe(target, "Hello");
CallMe obj2 = new CallMe(target, "Synchronized");
CallMe obj3 = new CallMe(target, "World");
try{
obj1.t.join();
obj2.t.join();
obj3.t.join();
}catch (InterruptedException e){
System.out.println("Interrupted Exception Caught");
}
}
}
The Required Output:
[Hello]
[Synchronized]
[World]
Actual Output (I am using Eclipse on Macbook Pro late 2013):
[Hello]
[World]
[Synchronized]
I have read that all these topic's output differ from computer to computer.
Could anyone please explain me why does not this work?