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

时间:2013-08-19 15:20:16

标签: 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();
    }
}

3 个答案:

答案 0 :(得分: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);  

答案 1 :(得分:2)

通常,如果ClassName.method是ClassName的静态方法,而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)

答案 2 :(得分:1)

这三个都是一样的。这些是引用当前正在执行的线程的不同方式。

相关问题