sleep()和wait()的区别?

本文详细解析了Java中线程的sleep与wait方法的区别。sleep方法使线程暂停执行指定时间,不释放对象锁;而wait方法则使线程放弃对象锁进入等待状态,直到收到通知。通过具体代码示例说明了两者的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间(Thread.sleep(1000)),把执行机会给其它线程,但监控状态依然保持,到时候自动恢复;调用sleep不会释放对象锁。
wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。
  1. public class Test {   
  2.   public static void main(String[] args) {   
  3.     new TestThread().start();   
  4.     new TestThread().start();   
  5.     new TestThread().start();   
  6.   }   
  7. }   
  8.   
  9. class TestThread extends Thread {   
  10.   private static Object lock = new Object();   
  11.   
  12.   public void run() {   
  13.     while (true) {   
  14.       try {   
  15.         Thread.sleep(1);   
  16.       } catch (Exception ex) {}   
  17.       synchronized (lock) {   
  18.         System.out.println(this.getId());   
  19.         try {   
  20.           notifyAll();   
  21.           this.wait();   
  22.           try {   
  23.             Thread.sleep(1);   
  24.           } catch (Exception ex) {}   
  25.         } catch (Exception ex) {}   
  26.         System.out.println(this.getId());   
  27.       }   
  28.     }   
  29.   }   
  30. }  
public class Test {
  public static void main(String[] args) {
    new TestThread().start();
    new TestThread().start();
    new TestThread().start();
  }
}

class TestThread extends Thread {
  private static Object lock = new Object();

  public void run() {
    while (true) {
      try {
        Thread.sleep(1);
      } catch (Exception ex) {}
      synchronized (lock) {
        System.out.println(this.getId());
        try {
          notifyAll();
          this.wait();
          try {
            Thread.sleep(1);
          } catch (Exception ex) {}
        } catch (Exception ex) {}
        System.out.println(this.getId());
      }
    }
  }
}
输出
9
9
10
10
8
8
10
10
8
8
9
9
8
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值