Why I'm not able to achieve Synchronization on this below piece of program:
class P
{
synchronized void pp(String s)
{
System.out.println (s);
}
}
class threadA extends Thread
{
P ob;
String s;
threadA (P ob, String s)
{
this.ob = ob;
this.s = s;
}
public void run ()
{
for (int i=1;i<=5;++i)
{
ob.pp (s);
try
{
Thread.sleep (1000);
}
catch (Exception e) {}
}
}
}
class gain
{
public static void main(String[] args) {
P ob = new P ();
threadA a = new threadA (ob,"Hello User");
threadA b = new threadA (ob,"Bye User");
a.start();
b.start();
}
}
OP:
Hello User
Bye User
Hello User
Bye User
Bye User
...
I want OP in the form of:
Hello User
Hello User
Hello User..
Bye User
Bye User
Bye User..
or my concept of synchronization is wrong?
ppmethod is synchronized so when you are waiting (in the sleep), nothing is synchronized. Seems you want to synchronized the "run" method so you could usesynchronized(ThreadA.class){ try{ ... }. But even this would not assure you thatastart beforeb