作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我是线程的初学者。我不知道线程对象调用 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();
}
}
最佳答案
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);
关于java - 线程中调用sleep方法的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18317398/
我是一名优秀的程序员,十分优秀!