• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

preculiar synchronized behaviour

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();
}
}
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
mohammed mustafa
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
drifter
Posts: 1364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic