[問題] SCJP 多執行緒問題
第233題
Given:
1. public class Threads1{
2. int x = 0;
3. public class Runner implements Runnable{
4. public void run(){
5. int current = 0;
6. for(int i=0; i<4; i++){
7. current = x;
8. System.out.print(current + ", ");
9. x = current + 2;
10. }
11. }
12. }
13.
14. public static void main(String[] args){
15. new Threads1().go();
16. }
17.
18. public void go(){
19. Runnable rl = new Runner();
20. new Thread(r1).start();
21. new Thread(r1).start();
22. }
23.}
Which two are possible results? (Choose two.)
A. 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
答案:AC
我的問題是在A,
我的認知是, main 方法中呼叫 go 方法
而 go方法依序 呼叫了 new Thread(r1).start();
new Thread(r1).start();
程式執行的順序是 第一條執行緒 跑了回圈三次 並對 x 及 current 變數做修改
再由第二條執行緒取得執行, 跑了迴圈四次
可是 A 最後一個輸出卻是 6
用eclipse 測試這個 code 也確實輸出會有遞增後又減少的情形
我想應該是我誤解程式執行的流程
想請問版上高手我錯誤的點在哪???
謝謝!!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.227.226.53
推
08/29 15:07, , 1F
08/29 15:07, 1F
→
08/29 15:08, , 2F
08/29 15:08, 2F
→
08/29 18:36, , 3F
08/29 18:36, 3F
→
08/29 22:33, , 4F
08/29 22:33, 4F
→
08/29 23:12, , 5F
08/29 23:12, 5F
討論串 (同標題文章)