aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread" Watch "Thread" New topic
Author

Thread

Sarikaa Bhatnagar
Greenhorn

Joined: May 10, 2005
Posts: 26
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
Sheriff

Joined: Sep 28, 2004
Posts: 19064
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread