Java 中 wait() 和 sleep() 方法有何区别?

javaobject oriented programmingprogramming更新于 2024/5/9 18:20:00

 sleep() 方法Thread  类的 静态方法,它可以将当前正在运行的线程置于"不可运行"状态,而  wait() 方法是一个实例方法,我们使用线程对象调用它,并且它只对该对象有影响。 sleep() 方法在时间到期后唤醒或调用 interrupt() 方法,而 wait()  方法在时间到期后唤醒或调用notify()notifyAll() 方法。 sleep() 方法在等待时不会释放任何 lock 或 monitor,而 wait() 方法在等待时会释放 lock 或 monitor。

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); // 调用 sleep() 方法
         this.wait(1000); // 调用 wait() 方法
         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

相关文章