2009年2月26日 星期四

第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; i27. 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".
答案:F
參考:13-4 執行緒的同步性與安全性

沒有留言:

張貼留言