GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes preculiar synchronized behaviour Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "preculiar synchronized behaviour" Watch "preculiar synchronized behaviour" New topic
Author

preculiar synchronized behaviour

mohammed mustafa
Greenhorn

Joined: Jan 11, 2001
Posts: 12
i am in a strange problem the code below creates two threads which try to execute synchronized method prin in class M1 but the threads are executing it simultaneously not after one thread finishes, please explain this behaviour
class M2 implements Runnable{
public M2(){
Thread t=new Thread(this);
t.start();}
public void run(){
M1 k=new M1();
k.prin();}
}
class M3 implements Runnable{
public M3(){
Thread t=new Thread(this);
t.start();}
public void run(){
M1 k=new M1();
k.prin();}
}
public class M1{
synchronized void prin(){
for (int i=0;i<1000;i++)
{System.out.print(i+" "); }
System.out.println("HELLO");
System.out.println("HOW ARE");
System.out.println("YOU ?");
}
public static void main(String ag[]){
M2 m=new M2();
M3 mm=new M3();
}
}
Arunagiri, Shanmugham
Ranch Hand

Joined: Jan 23, 2001
Posts: 46
Hi,
I compiled and executed your program, both threads are not running simultaneously in my system. I am using Windows NT.
Arun
SeE Consulting(P) Ltd


Sun Certified Programmer for Java2 Platform
mohammed mustafa
Greenhorn

Joined: Jan 11, 2001
Posts: 12
hi Arun, if you again check, the second thread is starting when the count on first thread is around 150 or so, this is what i mean as the second thread is not starting after the first thread has printed "HELLO"
" HOW ARE" "YOU?"
this is what i am getting on WIN ME, jdk1.3
mustafa
Carol Enderlin
drifter
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
The M2 and M3 Constructors each instantiate their own M1 object. M2 locks its M1 object and M3 locks its M1 object. Those locks do not conflict.
If they were both trying to call the prin method on the same M1 object (instead of on the two M1 objects) then the behavior would be as you expected.
 
GeeCON Prague 2014
 
subject: preculiar synchronized behaviour