>  기사  >  Java  >  Java에서 sleep()과 wait()의 차이점에 대한 자세한 설명

Java에서 sleep()과 wait()의 차이점에 대한 자세한 설명

黄舟
黄舟원래의
2017-09-21 09:28:091552검색

이 글은 Java에서 sleep()과 wait()의 차이점을 설명하는 관련 정보를 주로 소개합니다. 도움이 필요한 친구들은 이 글을 참조하세요.

Java에서 sleep()과 wait에 대한 자세한 설명 ()

sleep() 메소드의 경우 먼저 이 메소드가 Thread 클래스에 속한다는 것을 알아야 합니다. wait() 메소드는 Object 클래스에 속합니다.

sleep() 메서드는 프로그램이 지정된 시간 동안 실행을 일시 중지하고 CPU를 다른 스레드에 넘겨주지만 모니터링 상태는 계속 유지되며 지정된 시간이 지나면 자동으로 실행을 재개합니다.

sleep() 메서드를 호출하는 동안 스레드는 객체 잠금을 해제하지 않습니다.

wait() 메소드가 호출되면 스레드는 객체 잠금을 포기하고 이 객체를 기다리는 대기 잠금 풀에 들어갑니다. 이 객체에 대해 inform() 메소드가 호출된 후에야 스레드는 객체 잠금에 들어갑니다. 풀링하고 개체 잠금을 획득할 준비를 합니다.

무슨 뜻인가요?

설명 예:

/**
 * 
 */
package com.b510.test;

/**
 * java中的sleep()和wait()的区别
 * @author Hongten Java学习交流QQ群:589809992 我们一起学Java!
 * @date 2013-12-10
 */
public class TestD {

  public static void main(String[] args) {
    new Thread(new Thread1()).start();
    try {
      Thread.sleep(5000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    new Thread(new Thread2()).start();
  }

  private static class Thread1 implements Runnable{
    @Override
    public void run(){
      synchronized (TestD.class) {
      System.out.println("enter thread1...");  
      System.out.println("thread1 is waiting...");
      try {
        //调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池
        TestD.class.wait();
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("thread1 is going on ....");
      System.out.println("thread1 is over!!!");
      }
    }
  }

  private static class Thread2 implements Runnable{
    @Override
    public void run(){
      synchronized (TestD.class) {
        System.out.println("enter thread2....");
        System.out.println("thread2 is sleep....");
        //只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
        TestD.class.notify();
        //==================
        //区别
        //如果我们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,但是没有调用notify()
        //方法,则线程永远处于挂起状态。
        try {
          //sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,
          //但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
          //在调用sleep()方法的过程中,线程不会释放对象锁。
          Thread.sleep(5000);
        } catch (Exception e) {
          e.printStackTrace();
        }
        System.out.println("thread2 is going on....");
        System.out.println("thread2 is over!!!");
      }
    }
  }
}

실행 효과:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!

코드를 주석 처리하는 경우:

1 TestD.class.notify();

실행 효과:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!

프로그램은 항상 보류 상태입니다.

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.