wait() vs sleep()

wait(timeout)

释放对象锁

import lombok.SneakyThrows;

/*
线程1进入等待状态
线程2 hello
线程1 over
**/
public class T {
    @SneakyThrows
    public static void main(String[] args) {
        Object o = new Object();
        Thread thread1 = new Thread(() -> {
            try {
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + "进入等待状态");
                    o.wait(5000);
                    System.out.println(Thread.currentThread().getName() + " over");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, "线程1");

        Thread thread2 = new Thread(() -> {
            synchronized (o) {
                try {
                    System.out.println(Thread.currentThread().getName() + " hello");
                } catch (Exception e) {

                }
            }
        }, "线程2");

        thread1.start();
        thread2.start();
    }
}

sleep()

不会释放对象锁

import lombok.SneakyThrows;

/*
线程1进入等待状态
线程1 over
线程2 hello
* */
public class T {
    @SneakyThrows
    public static void main(String[] args) {
        Object o = new Object();
        Thread thread1 = new Thread(() -> {
            try {
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + "进入等待状态");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getName() + " over");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, "线程1");

        Thread thread2 = new Thread(() -> {
            synchronized (o) {
                try {
                    System.out.println(Thread.currentThread().getName() + " hello");
                } catch (Exception e) {

                }
            }
        }, "线程2");

        thread1.start();
        thread2.start();
    }
}
posted @ 2024-08-14 11:32  干饭达人GoodLucy  阅读(8)  评论(0)    收藏  举报