Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
Sarikaa Bhatnagar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • 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.
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic