Java中的wait()和sleep()方法之间的区别?

 sleep()方法 静态 的方法线程 类,它可以把当前正在运行的线程进入一个“非可运行”状态 ,而 wait()的方法是一个实例方法,我们使用线程对象的调用它,它只是影响对于那个对象。超时后的sleep()方法唤醒或调用 interrupt() 方法,而超时后的wait() 方法唤醒或调用notify()notifyAll() 方法。的睡眠()方法不会释放任何锁定或monito ř在等待而等待() 方法在等待时释放锁或监视器。

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