SCJP題庫第233題

 
Given:
1. public class Threads1{
2.   int x = 0;
3.   public class Runner implements Runnable{
4.     public void run(){
S.       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,
Ans: AC

解說:第20與21行各新增一條執行緒,共同執行同樣的程式與資料(r1的run方法與r1物件的x物件變數),


第6~10行的迴圈共執行4次,二條執行緒若各跑4次,輸出也最多八次,D/E的答案不可能。


A/B/C選二個,觀察x變數,由於二條執行共用此x,所以不管是執行緒1或2只會對x變數增加,輸出應呈現增加的狀況,B基本上不可能。

Comments

Popular posts from this blog

Android-使用webview在V3版的Google地圖GPS定位