• 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

Thread

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

PLs help with this,

class MyClass
{

static private int mycount = 0;
int yournumber;

private static synchronized int nextCount()
{
return ++mycount;
}

public void getYourNumber()
{
yournumber = nextCount();
}

}

The correct answer is "each thread will get a unique number". Can someone explain why ? I think that as the "getYourNumber()" is not synchronized so many thread can access it at the same time and can get the same number. I am assuming that as "nextCount" is private so no thread is accessing it directly to get the unique count.

thanks,
Sarika.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I am assuming that as "nextCount" is private so no thread is accessing it directly to get the unique count.



What does a "private" accessor have to do with threading? "private" means that that the method can only be called by other methods of the same class -- it is private to the class.

All the threads calling getYourNumber() indeed run in parallel, until they (in the getYourNumber() method) call nextCount(), then they synchronize on the same class lock. And hence, get a unique number.

Henry
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic