This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 18500
    
  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
 
Similar Threads
Brodgen's Exam Cram:- Sample Test :- Page:- 310. Q.6
Question on Threads
threads
question about thread at J@Whiz1.4
Word Counter