>  기사  >  Java  >  Java에서 sleep()과 wait()의 차이점은 무엇입니까

Java에서 sleep()과 wait()의 차이점은 무엇입니까

WBOY
WBOY앞으로
2023-04-29 08:37:062116검색

차이점 설명

1. wait()는 Object의 메소드이고, sleep()은 Thread의 메소드입니다.

2. Wait()는 동기 방식을 사용해야 하며, sleep() 방식은 필요하지 않습니다.

3. 스레드는 모니터 잠금을 해제하지 않고 동기화 메서드에서 sleep() 메서드를 실행합니다.

짧은 절전 후 sleep() 메서드는 차단을 적극적으로 종료하는 반면, wait() 메서드는 차단을 종료하기 위한 대기 시간을 지정하지 않고 다른 스레드에 의해 중단되어야 합니다.

인스턴스

import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleepAndWait {
public static void main(String[] args) {
new Thread1().start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread2().start();
}
}
class Thread1 extends Thread{
private void sout(String s){
System.out.println(s+" "+new SimpleDateFormat("HH:mm:ss:SS").format(new Date()));
}
@Override
public void run() {
sout("enter Thread1.run");
synchronized (TestSleepAndWait.class){//wait只能在同步代码块或者同步方法中使用
sout("Thread1 is going to wait");
try {
TestSleepAndWait.class.wait(); // 这里只能使用持有锁TestSleepAndWait.class.wait(),使用其他对象则报错java.lang.IllegalMonitorStateException
} catch (InterruptedException e) {
e.printStackTrace();
}
sout("after waiting, thread1 is going on");
sout("thread1 is over");
}
}
}
class Thread2 extends Thread{
private void sout(String s){
System.out.println(s+" "+new SimpleDateFormat("HH:mm:ss:SS").format(new Date()));
}
@Override
public void run() {
sout("enter Thread2.run");
synchronized (TestSleepAndWait.class){//wait只能在同步代码块或者同步方法中使用
sout("Thread2 is going to notify");
TestSleepAndWait.class.notify(); 这里只能使用持有锁TestSleepAndWait.class
sout("thread2 is going to sleep 10ms");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sout("after sleeping, thread2 is going on");
sout("thread2 is over");
}
}
}

위 내용은 Java에서 sleep()과 wait()의 차이점은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제