jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes confusion in synchronized  blocks.....in Threads...HELP... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "confusion in synchronized  blocks.....in Threads...HELP..." Watch "confusion in synchronized  blocks.....in Threads...HELP..." New topic
Author

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

vikas mehta
Greenhorn

Joined: Dec 28, 2001
Posts: 4
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

Joined: Oct 25, 2000
Posts: 7292

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).]


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: confusion in synchronized blocks.....in Threads...HELP...
 
Similar Threads
THREADS :PLEASE HELP
Question from Khalid book
Doubt in Threads
confused on thread topic
not at all able to understand what is happening in this program