SCJP題庫第236題

 
Given:
1. class Computation extends Thread{
2.
3.     private int num;
4.     private boolean isComplete;
5.     private int result;
6.
7.     public Computation(int num){this.num = num;}
8.
9.     public synchronized void run(){
10.     result = num * 2;
11.     isComplete = true;
12.     notify();
13.   }
14.
15.   public synchronized int getResult(){
16.      while(!isComplete){
17.         try{
18.            wait();
19.         }catch(InterruptedException e){}
20.     }
21.     return result;
22.   }
23.
24.   public static void main(String[] args){
25.      Computation[] computations = new Computation[4];
26.      for(int i=0; i<computations.length; i++){
27.         computations[i] = new Computation(i);
28.         computations[i].start();
29.      }
30.      for(Computation c : computations)
31.         System.out.print(c.getResult() + " ");
32.      }
33.   }


What is the result?
 
A. The code will deadlock.
B. The code may run with no output.
C. An exception is thrown at runtime.
D. The code may run with output "0 6".
E. The code may run with output "2 0 6 4".
F. The code may run with output "0 2 4 6".
Ans: F

解說:第25~29行建立四個Thread物件,然後分別啟動這四個執行緒物件…


緊接著30~31行分別讓四個執行緒物件呼叫getResult方法,然後分別進入對各自執行緒物件的等待事件中…


最後四個執行緒的run方法分別通知各自執行緒離開wait狀態…


比較可能的輸出是F,因為各執行緒物件的num是依for迴圈0~3再乘以2得來,輸出依0 2 4 6的機率較高。







Comments

Popular posts from this blog

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