gpt4 book ai didi

java - 线程中调用sleep方法的不同方式

转载 作者:搜寻专家 更新时间:2023-10-31 19:28:42 27 4
gpt4 key购买 nike

我是线程的初学者。我不知道线程对象调用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com