Question ID :971037111660
public class TestClass implements Runnable
{
int x = 0, y = 0;
public void run()
{
while(true)
{
synchronized(this)
{
x++; y++;
System.out.println(" x = "+x+" , y = "+y);
}
}
}
public static void main(
String[] args)
{
TestClass tc = new TestClass();
new
Thread(tc).start();
new Thread(tc).start();
}
}
options given are -
1.It will throw exception at runtime as two threads cannot be created at the same time.
2.It will keep on printing values which show x and y as always equal and increasing by 1 at each line.
3.It will keep on printing values which show x and y as different.
4.Nothing can be said abt the sequence
5.It will keep on printing which show x and y as always equal but may increase more than one at each line.
Answer is 2 acc to JQplus. Reason: Here, the access to shared variables x and y is in syncronized block so when any thread gets access to the block it increments both x and y before the other thread can touch the block. This makes sure that the values of x and y are always same and they increase one by one.
I agree with the above line of reasoning and had worked out the same logic till this point. But the phrasing of answer has has missed out one aspect. The answer seems to imply that the output will be printed for each thread as if one thread is executing one after the other cleanly. But the JVM could always switch between the execution of the threads, due to its time slicing, such that the output would look like this
x=0,y=0 (for thread 1)
x=1,y=1 (for thread 1)
x=0,y=0 (for thread 2)
x=2,y=2(fpr thread 2) and so on.
So option 2 which assumes that the values of x and y increase by one
on each line seems incorrect.(in the above example, the output on the line is not necessarily from the same thread and it is not increasing consistently from one line to the next).
So this is why I chose option 4. If option 2 is rephrased such that it specifies that the x and y for a given thread increase by 1 and the words 'on each line' are removed, then it would be correct.
I am hoping for ranch members comments on this. Paul, could also give your opinion on this ?
Thanks everyone!
Sajida