• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
vikas mehta
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • 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();
}
}
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • 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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic