Thread.sleep() 및 wait()의 차이점이 있습니다.대기 및 스레드 정확한 차이
The code sleep(1000);
puts thread aside for exactly one second.
The code wait(1000);
causes a wait of up to one second.
wait 이외의 것이 객체 클래스이고 Thread 클래스의 sleep이란 정확히 무엇입니까?
좋은 예가 있습니까?
Thread.sleep() 및 wait()의 차이점이 있습니다.대기 및 스레드 정확한 차이
The code sleep(1000);
puts thread aside for exactly one second.
The code wait(1000);
causes a wait of up to one second.
wait 이외의 것이 객체 클래스이고 Thread 클래스의 sleep이란 정확히 무엇입니까?
좋은 예가 있습니까?
wait()
은 notify()
또는 notifyAll()
을 호출하여 각성 될 수 있습니다. 이 예에서는 Blah1이 1000 밀리 초를 기다리지 않음을 알 수 있습니다. 왜냐하면 이전에 Blah2에 의해 각성되기 때문입니다. Blah2 기다립니다.
wait()
메서드는 지정된 스레드에 의해 차단되는 모니터를 해제합니다. sleep()
않습니다.
sleep()
은 interrupt()
메서드를 호출하여 인터럽트 할 수 있습니다.
public class Blah implements Runnable {
private String name;
public Blah(String name) {
this.name = name;
}
synchronized public void run() {
try {
synchronized (Blah.class) {
System.out.println(name + ": Before notify " + new Date().toString());
Blah.class.notifyAll();
System.out.println(name + ": Before wait " + new Date().toString());
Blah.class.wait(1000);
System.out.println(name + ": After " + new Date().toString());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread th1 = new Thread(new Blah("Blah1"));
Thread th2 = new Thread(new Blah("Blah2"));
th1.start();
th2.start();
}
}
출력 :
Blah1: Before notify Tue Jan 13 09:19:09 CET 2015
Blah1: Before wait Tue Jan 13 09:19:09 CET 2015
Blah2: Before notify Tue Jan 13 09:19:09 CET 2015
Blah2: Before wait Tue Jan 13 09:19:09 CET 2015
Blah1: After Tue Jan 13 09:19:09 CET 2015
Blah2: After Tue Jan 13 09:19:10 CET 2015
'wait()'는 쓰레드를 정확히 차단합니다. – chrylis
맞아, 나는 내 마음에 뭔가있어. –
'Sleep()'도 인터럽트 할 수 있습니다 *. – TheLostMind
당신이에 동기화 된 객체에 wait()
호출하고 notify()
또는 notifyAll()
A에 대한 모니터와 대기를 해제가 같은 개체에서 호출 할 수 있습니다. 일반적으로 요청이나 연결 대기열과 같은 일부 공유 객체에서 활동을 조정하는 데 사용됩니다.
sleep()
은 모니터를 해제하지 않거나 다른 스레드와 직접 상호 작용하지 않습니다. 대신, 모든 모니터를 보유하고 조금만 현재 스레드를 실행하는 것을 중지합니다.
출시 모니터는 내 첫 번째 대답에서 내 마음에 있던 것입니다 :) 감사합니다. 커피가 필요해. –
Javadocs는 차이점을 분명히합니다. – chrylis