Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

 
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();
}
}
 
High Plains Drifter
Posts: 7289
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).]
 
To avoid criticism do nothing, say nothing, be nothing. -Elbert Hubbard. Please critique this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic