5

我是线程的初学者。我不知道线程对象调用睡眠方法的三种不同类型的方式有什么区别。另外,您能否澄清在哪种类型的情况下,使用调用 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();
    }
}
4

3 回答 3

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);  
于 2013-08-19T15:24:04.327 回答
2

一般来说,如果ClassName.method是ClassName的静态方法,并且x是类型为的表达式ClassName,那么你可以使用x.method()它,它和调用一样ClassName.method()。的值是什么并不重要x;该值被丢弃。即使xis也会起作用null

String s = null;
String t = s.format ("%08x", someInteger);  // works fine 
                                            // (String.format is a static method)
于 2013-08-19T15:55:29.483 回答
1

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

于 2013-08-19T15:25:41.997 回答