Q. Here we have a CallMe class which have a call method,another class Caller implementing Runnable interface , it has a
String variable.In main class three Threads have been created & initialised to different strings, now the run method creates objects of CallMe class & call method -> call which is synchronized but it is not working in a synchronized way.As the output shows.
class CallMe {
Synchronized void call(String s) {
System.out.println("["+s);
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("]");
}
}
class Caller implements Runnable {
String str;
Caller(String s) {
str = s;
}
public void run() {
new CallMe().call(str);
}
}
class Pg240 {
public static void main(String args[]) {
CallMe cm = new CallMe();
Caller ob1 = new Caller("AMIT SETHI");
Caller ob2 = new Caller("HARISH SETHI");
Caller ob3 = new Caller("HEMANT SETHI");
Thread t1 = new Thread(ob1);
Thread t2 = new Thread(ob2);
Thread t3 = new Thread(ob3);
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
}
catch(InterruptedException e) {
System.out.println("main interrupted");
}
}
}
output :without synchronised:
F:\j5se\cr>javac Pg240.java
F:\j5se\cr>
java Pg240
[AMIT SETHI
[HARISH SETHI
[HEMANT SETHI
]
]
]
output :with synchronised: (both are same why ?)
F:\j5se\cr>javac Pg240.java
F:\j5se\cr>java Pg240
[AMIT SETHI
[HARISH SETHI
[HEMANT SETHI
]
]
]
pls help me .
Thanks in advance.
regards
Amit Sethi