2013-08-19 61 views
5

我是一個線程初學者。我不知道線程對象稱爲睡眠方法的三種不同方式之間的區別。還可以請你澄清在案件類型上有使用睡眠方法被調用線程中調用睡眠方法的不同方法

方式下面

// implementing thread by extending THREAD class// 

class Logic1 extends Thread 
{ 
    public void run() 
    { 
     for(int i=0;i<10;i++) 
     { 
      Thread s = Thread.currentThread(); 
      System.out.println("Child :"+i); 
      try{ 
       s.sleep(1000);    // these are the three types of way i called sleep method 
       Thread.sleep(1000);   //  
       this.sleep(1000);   // 
      } catch(Exception e){ 

      } 
     } 
    } 
} 

class ThreadDemo1 
{ 
    public static void main(String[] args) 
    { 
     Logic1 l1=new Logic1(); 
     l1.start(); 
    } 
} 
+2

'sleep()'是一個總是引用當前正在執行的線程的靜態方法。 –

+0

沒有三種方法可以調用sleep方法,Thread#sleep是static方式,所以你可以直接從'Thread'類或從當前'Thread'對象引用中調用它。 –

+0

都是一樣的。 :D – gumuruh

回答

7

sleep()的代碼給出的限制是一個靜態方法,它一直引用當前執行線程。

根據JavaDoc:

/** 
* Causes the currently executing thread to sleep (temporarily cease 
* execution) for the specified number of milliseconds, subject to 
* the precision and accuracy of system timers and schedulers. The thread 
* does not lose ownership of any monitors. 
* 
* @param millis 
*   the length of time to sleep in milliseconds 
* 
* @throws IllegalArgumentException 
*   if the value of {@code millis} is negative 
* 
* @throws InterruptedException 
*   if any thread has interrupted the current thread. The 
*   <i>interrupted status</i> of the current thread is 
*   cleared when this exception is thrown. 
*/ 
public static native void sleep(long millis) throws InterruptedException; 

這些調用

s.sleep(1000); // even if s was a reference to another Thread 
Thread.sleep(1000);  
this.sleep(1000);  

都相當於

Thread.sleep(1000); 
+0

謝謝,但如果我實現runnable接口,而不是擴展線程類,並直接使用睡眠(1000);那麼它就是說沒有找到睡眠方法,爲什麼它會發展起來 –

+3

因爲'Runnable'接口沒有'sleep(long)'方法。 '線程'有它。 –

1

這三種方法都相同。這些是引用當前正在執行的線程的不同方式。

2

一般來說,如果ClassName.method是類名的靜態方法,且x是類型爲ClassName一個表達式,則可以使用x.method(),這將是與調用ClassName.method()。不要緊,x的值是多少;該值被丟棄。即使xnull,它也可以工作。

String s = null; 
String t = s.format ("%08x", someInteger); // works fine 
              // (String.format is a static method)