This is Q58 of the diagnostic exam:
class ThreadDemo {
private int count = 1;
public synchronized void doSomething()
{
for (int i = 0; i < 10; i++)
System.out.println(count++);
}
public static void main(
String[] args)
{
ThreadDemo demo = new ThreadDemo();
Thread a1 = new A(demo);
Thread a2 = new A(demo);
a1.start();
a2.start();
}
}
class A extends Thread
{
ThreadDemo demo;
public A(ThreadDemo td)
{
demo = td;
}
public void run()
{
demo.doSomething();
}
}
A. It will print 0 to 19 sequentially.
B. It will print 1 to 20 sequentially.
C. It will print 1 to 20, but order cannot be determined.
D. It will print 0 to 19, but order cannot be determined.
E. The code will not compile.
If I'm not wrong, the answer should be B. What I want to ask is: wouldn't the synchronized method doSomething() give the same result if the method is NOT synchronized? (since both threads took the same reference of demo and share the instance for variable count)