sleep() 메서드 정적 입니다. 스레드 메소드 현재 실행 중인 스레드를 "실행 불가" 상태 로 보낼 수 있습니다. 반면 wait() 메서드는 인스턴스 메서드이고 스레드 개체를 사용하여 호출하고 있으며 해당 개체에 대해서만 영향을 받습니다. 수면() 시간이 만료된 후 메서드 깨우기 또는 interrupt() 호출 메소드인 반면 wait() 시간 만료 후 메서드 깨우기 또는 notify() 호출 또는 notifyAll() 방법. 수면() 메소드가 잠금 또는 모니터링을 해제하지 않습니다. r 기다리는 동안 wait() 메서드는 기다리는 동안 잠금 또는 모니터를 해제합니다.
sleep() 메서드 구문
public static void sleep(long millis) throws InterruptedException
wait() 메서드 구문
public final void wait() throws InterruptedException
예
public class ThreadTest implements Runnable {
private int number = 10;
public void methodOne() throws Exception {
synchronized(this) {
number += 50;
System.out.println("Number in methodOne(): " + number);
}
}
public void methodTwo() throws Exception {
synchronized(this) {
Thread.sleep(2000); // calling sleep() method
this.wait(1000); // calling wait() method
number *= 75;
System.out.println("Number in methodTwo(): " + number);
}
}
public void run() {
try {
methodOne();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ThreadTest threadTest = new ThreadTest();
Thread thread = new Thread(threadTest);
thread.start();
threadTest.methodTwo();
}
} 출력
Number in methodOne(): 60 Number in methodTwo(): 4500