i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.
class ABC {
synchronized public void meth(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
}
System.out.println("]");
}
}
class SyncMethod implements Runnable {
ABC a = new ABC();
Thread t;
SyncMethod(String s) {
t = new Thread(this, s);
t.start();
}
public void run() {
a.meth(t.getName());
}
public static void main(String args[]) {
new SyncMethod("Hello");
new SyncMethod("Synchronized");
new SyncMethod("World");
}
}
Current Output :
[Hello [Synchronized [World] ] ] ]
Desired Output :
[Hello]
[Synchronized]
[World]