Различные способы вызова метода 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 ответа:
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);
В общем случае, если
ClassName.methodявляется статическим методом ClassName, аxявляется выражением, тип которогоClassName, то вы можете использоватьx.method(), и это будет то же самое, что вызовClassName.method(). Не имеет значения, каково значениеx; Значение отбрасывается. Он будет работать, даже еслиxявляетсяnull.String s = null; String t = s.format ("%08x", someInteger); // works fine // (String.format is a static method)