SCJP題庫第225題

 
Given:
8.  Runnable r = new Runnable() {
9.      public void run() {
10.          try {
11.              Thread.sleep(1000);
12.          } catch(InterruptedException e) {
13.              System.out.println(“interrupted”);
14.          }
15.          System.out.println(“ran”);
16.      }
17.  };
18.  
19.  Thread t = new Thread(r);
20.  t.start();
21.  System.out.println(“started”);
22.  try {
23.      t.sleep(2000);
24.  }
25.  catch(Exception e) {}
26.  System.out.println(“interrupting”);
27.  t.interrupt();
28.  System.out.println(“ended”);


Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time. Place the fragments in the output area to show the result of running this code.
Ans:


解說:
題目問設sleep(n)n毫秒內執行完閉,所有其他的程式碼在少量的時間內執行完閉,輸出應該是什麼?

上面的程式完整的寫法如下:

class threadTest{
public static void main(String[] args){
Runnable r = new Runnable(){
public void run(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("interrupted");
}
System.out.println("ran");
}
};
Thread t = new Thread(r);
try{
t.start();
} catch (Exceotion e){
System.out.println("started");
}
t.sleep(2000);
System.out.println("interrupting");
t.interrupt();
System.out.println("ended");
}
}

t執行緒被啟動後,執行1秒的睡眠,main執行緒執行2秒的睡眠(t.sleep(2000)),基本上t執行緒會先離開睡眠,而執行印出ran

之後main離開睡眠狀態,印出interrupting
再發出一個interrupt(因為t已經離開睡眠狀態,這個interrupt不會造成t的睡眠狀態中斷,而印出interrupted。

main印出ended…


Sleep是Thread的靜態方法不是物件方法,使用方法應為Thread.Sleep(n),第23行行t.sleep(1000)等同於Thread.Sleep(1000)。

Comments

Popular posts from this blog

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