SCJP題庫第235題
Given:
11. public class PingPong implements Runnable{
12. synchronized void hit(long n){
13. for(int i=1; i<3; i++)
14. System.out.print(n + "-" + i + " ");
15. }
16. public static void main(String[] args){
17. new Thread(new PingPong()).start();
18. new Thread(new PingPong()).start();
19. }
20. public void run(){
21. hit(Thread.currentThread().getId);
22. }
23. }
Which two statements are true? (Choose two.)
A. The output could be 8-1 7-2 8-2 7-1
B. The output could be 7-1 7-2 8-1 6-1
C. The output could be 8-1 7-1 7-2 8-2
D. The output could be 8-1 8-2 7-1 7-2
Ans: CD
解說: run方法會去呼叫同步方法hit,二條執行緒各自有獨立的hit方法執行,i必然是依1與2的順序輸出,A答案中執行緒7先跑2再跑1是錯的,答案B出現一條執行緒6,程式只建二條執行緒不可能出現第3條執行緒。
Comments