wait() vs sleep()

干饭达人GoodLucy發表於2024-08-14

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();
    }
}

相關文章