Redian新闻
>
问个Thread 的问题,java certificate里的
avatar
问个Thread 的问题,java certificate里的# Java - 爪哇娇娃
o*a
1
1. 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 sa
avatar
J*a
2
记得这个问题有争论,win和linux的线程模式不一样,你换到后者上面
执行就会结果不同了
在win上肯定是d,原因就是两个线程级别相同...

【在 o*a 的大作中提到】
: 1. 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.

avatar
n*k
3

the
on
on
only
x++
y
I am pretty sure the key is wrong.
You can varify that by either adding
if (x! = y)
System.out.println("x = " + x + " y = " + y);
insider the run method.
or Thread.currentThread().sleep(100); between x ++ and y++,
You will see that x and y will have difffernt value.
Hope this will help.

【在 o*a 的大作中提到】
: 1. 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.

avatar
m*t
4

I believe it has more to do with the facts that both threads
are started almost immediately back to back, that they run
on exactly the same code, and that there probably wasn't a lot
of other things running when this test program was executed.
If you insert a random sleep between
x++ and y++, it'll make some difference.

【在 J*****a 的大作中提到】
: 记得这个问题有争论,win和linux的线程模式不一样,你换到后者上面
: 执行就会结果不同了
: 在win上肯定是d,原因就是两个线程级别相同...

avatar
J*a
5
if you insert some random sleeps, i should be different, but it's not
the same env.
the orginal is the circle time is what jvm excute x++ and y++, and
the later should plus a random paremeter.
in my remember, one of win and linux's thread mode is 抢占式, so ...

【在 m******t 的大作中提到】
:
: I believe it has more to do with the facts that both threads
: are started almost immediately back to back, that they run
: on exactly the same code, and that there probably wasn't a lot
: of other things running when this test program was executed.
: If you insert a random sleep between
: x++ and y++, it'll make some difference.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。