在线程中调用sleep方法的不同方法

ros*_*dhb 5 java multithreading thread-sleep

我是线程的初学者.我不确切地知道线程对象调用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 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;
Run Code Online (Sandbox Code Playgroud)

这些电话

s.sleep(1000); // even if s was a reference to another Thread
Thread.sleep(1000);      
this.sleep(1000);     
Run Code Online (Sandbox Code Playgroud)

都等同于

Thread.sleep(1000);  
Run Code Online (Sandbox Code Playgroud)

  • 因为`Runnable`接口没有`sleep(long)`方法.`Thread`有它. (3认同)