Follow is the question:
Multiple objects of MyClass (given below) are used in a program that uses multiple Threads to create new integer count. What will happen when other threads use the following code?
class MyClass
{
static private int myCount = 0;
int yourNumber;
private static synchronized int nextCount()
{
return ++myCount;
}
public void getYourNumber()
{
yourNumber = nextCount();
}
}
C) Each
thread will get a unique number.
D) The uniqueness of the number among different Threads can't be guaranteed.
the correct answer is C),but I think it should be D),because if one thread want to get the mycount,it must initial an instanse of class MyClass,eg,mc,then mc.yourNumber.but at that time other thread may modified the value of yourNumber not use the method getYourNumber.so...,
please help me!thanx.