请教:scjp中一道常见的多线程问题,不大明白 :)
6 of 62、 What is the result?
public class MultiThread implements Runnable
{
private int x;
private int y;
public static void main(String args[])
{
MultiThread one = new MultiThread();
(new Thread(one)).start();
(new Thread(one)).start();
}
public void run()
{
for(;;)
{
x++;
//难道在这时候不会转换线程?
y++;
System.out.println("x=" + x +" , y=" + y);
}
}
}
A. Errors at lines 7 and 8 cause compilation to fail.
B. The program prints pairs of values for x and y that might not always be the same
on the same line (for example, “x=2, y=1”).
C. The program prints pairs of values for x and y that are always the same on the
same line (for example, “x=1, y=1”. In addition, each value appears twice (for
example, “x=1, y=1” followed by “x=1, y=1”).
D. The program prints pairs of values for x and y that are always the same on the
same line (for example, “x=1, y=1”. In addition, each value appears only for
once (for example, “x=1, y=1” followed by “x=2, y=2”).
正确答案: D
若在我注释的地方,线程转换了,那么x就会被执行两次 x++; 这样的话打出来的就不会每次都相等,所以,这道题,我认为应该选B。 可是很多模拟题给的正确答案都是 D 。郁闷!
能把我说服就给分结贴,谢谢!