• 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

confusion in synchronized blocks.....in Threads...HELP...

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this code is from khalid mughal threads question
i m basically not able to understand what are synchronized blocks and methods...though theoratically clear but not when it comes to coding...
i would like to know what happens when the following code is run and why...
plz detail each line of code so that i m able to understand..specially the two methods....
public class myclass extends Thread
{
static Object lock1=new Object();
static Object lock2=new Object();
static volatile int i1,i2,j1,j2,k1,k2;
public void run()
{
while(true)
{
doit();
check();
}
}
void doit()
{
synchronized(lock1)
{
i1++;
}
j1++;
synchronized(lock2)
{
k1++;
k2++;
}
j2++;
synchronized(lock1)
{
i2++;
}
}
void check()
{
if(i1!=i2)
System.out.println("i");
if(j1!=j2)
System.out.println("j");
if(k1!=k2)
System.out.println("k");
}
public static void main(String[] args)
{
new myclass().start();
new myclass().start();
}
}
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Vikas -
This code sample gets posted all the time -- it's a bit of a brain teaser and generates a lot of questions in this forum. Here is a link that refers several answers to your question. You should find more than enough to go on from that.
Happy New Year!
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
[This message has been edited by Michael Ernest (edited December 31, 2001).]
 
reply
    Bookmark Topic Watch Topic
  • New Topic