首页 > 文章列表 > 在Java中,wait()和sleep()方法之间的区别是什么?

在Java中,wait()和sleep()方法之间的区别是什么?

java sleep 区别:wait
486 2023-08-30

sleep()方法Thread类的一个静态方法,它可以发送当前运行的数据线程进入“不可运行”状态,而 wait()方法是一个实例方法,我们使用线程对象调用它,并且它仅对该对象产生影响。 sleep() 方法在时间到期后唤醒或调用  interrupt()  方法,而 wait()  方法在时间到期后唤醒或调用 >notify()notifyAll() 方法。 sleep() 方法在等待时不会释放任何锁或监视器,而 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