sleep和wait的区别

    技术2025-12-16  3

    关于锁

    public class SleepWaitDemo { public static void main(String[] args) { Object o = new Object(); new Thread(() -> { System.out.println("thread a is waiting to get lock"); synchronized (o) { try { System.out.println("thread a is get lock"); Thread.sleep(20); System.out.println("thread a is do wait method"); o.wait(1000); // Thread.sleep(1000); System.out.println("thread a is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { System.out.println("thread b is waiting to get lock"); synchronized (o) { try { System.out.println("thread b is get lock"); System.out.println("thread b is sleep 10 ms"); Thread.sleep(10); // o.wait(10); System.out.println("thread b is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }

    打印结果

    thread a is waiting to get lock thread a is get lock thread b is waiting to get lock thread a is do wait method thread b is get lock thread b is sleep 10 ms thread b is done thread a is done

    可以看到当执行a执行wait后,不光会释放cpu资源,还会释放锁,让b拿到锁

    改变代码,改为让a执行sleep,b执行wait

    public class SleepWaitDemo { public static void main(String[] args) { Object o = new Object(); new Thread(() -> { System.out.println("thread a is waiting to get lock"); synchronized (o) { try { System.out.println("thread a is get lock"); Thread.sleep(20); System.out.println("thread a is do wait method"); // o.wait(1000); Thread.sleep(1000); System.out.println("thread a is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { System.out.println("thread b is waiting to get lock"); synchronized (o) { try { System.out.println("thread b is get lock"); System.out.println("thread b is sleep 10 ms"); // Thread.sleep(10); o.wait(10); System.out.println("thread b is done"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }

    打印结果

    thread a is waiting to get lock thread a is get lock thread b is waiting to get lock thread a is do wait method thread a is done thread b is get lock thread b is sleep 10 ms thread b is done

    sleep不会释放锁,等a执行完了才释放锁

    Processed: 0.011, SQL: 12