2013-08-19 7 views
5

私はスレッド化の初心者です。スレッドオブジェクトがスリープメソッドと呼んでいた3つの異なるタイプの違いが何であるかはわかりません。また、あなたは、コードがスレッド内でsleepメソッドを呼び出す方法が異なります

// 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'メソッドを呼び出す3つの方法はありません。' 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);  

は、すべての3つが同じであるすべての

Thread.sleep(1000); 
+0

ありがとう、しかし、スレッドクラスを拡張するのではなく、runnableインターフェイスを実装し、直接sleep(1000)を使用しています。 'sleep(long)'メソッドを持たないため、sleepメソッドが見つかりませんでした。理由は何ですか? –

+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) 
関連する問題