This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Journey To Enterprise Agility and have Daryl Kulak & Hong Li on-line!
See this thread for details.
Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Variable increment problem (threads)  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a problem in my project.Some thing like I will be spawning n number of threads.These threads have a increment two variables x and y.And these threads have to run infinitly each time incrementing and using those variables.After some time I am getting these variables being increments out of sync though i am incrementing them in a syncronized method.
ex: if I give initial variables as x = 100 and y =200.after running the program say after 5 min those variables are becoming something like 144 & 251 but I am expecting them to be 191 & 291.
my method is like this

static long x = 0;
static long y = 0;
public void run()
{
while(true)
{ increment();//increments the variables }
if(someCondition)
{ thread.yield(); return;//terminating execution }
}

static synchronized increment()
{
x++;
y++;
}
 
author and iconoclast
Sheriff
Posts: 24220
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They should appear to be in sync to any thread that reads them in a matching synchronized method or block.

Please don't post the same question in multiple forums. I'm going to move this one to the Threads forum and delete the other copy.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!