请高手看这个线程问题

来源:百度知道 编辑:UC知道 时间:2024/06/23 04:15:46
public class X implements Runnable(

2. private int x;

3. private int y;

4.

5. public static void main(String[]args)

6. X that = new X();

7. (new Thread(that)).start();

8. (new Thread(that)).start();

9. )

10.

11. public void run() (

12. for (;;) (

13. x++;

14. y++;

15. System.out.printIn(“x=” + x + “, y = ” + y);

16. )

17. )

18. )

What is the result?

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

虽然创建了两个线程,但他们使用的是同一个对象数据,即都是that.
所以他们共享了that的run()方法.
打印一份是必然的了,假如第一个线程己经是x=2,y=2了,这时第二个线程运行时,会直接在2的基础上再加1,所以为x=3,y=3了,当第一个线程执行时同理推.
其实你这个程序有问题,或者答案有问题,我觉B是对的.因为:
假如第一个线程执行到循环的y++之后,而并未执行输出时,第二个线程占用了CPU(线程占用CPU是随机的),然后他执行到x++之后,y++之前,此时x++执行了两次而y++只执行了一次所以当前状态为:x=2,y=1;当第一个线程获得CPU时间继续输出时就会出现这种情况.当然按昭你这个程序这种情况的概率很小,但并不是说不可能,作为一个题目的话B应该是正确答案.
不知你是从哪弄来的题,如果是你们老师教的话,你可以和他评理,说不清就叫他看看我写的.
我相信我自己.

因为线程是共享相同数据的