sleep()和wait()區別

干饭达人GoodLucy發表於2024-08-17
import lombok.*;

/*
o.wait();釋放鎖
    ...
Thread.sleep(6000);
    6004
    ...
* */
public class T {
    @SneakyThrows
    public static void main(String[] args) {
        Object o = new Object();
        new Thread(() -> {
            synchronized (o) {
                try {
                    long begin = System.currentTimeMillis();
                    Thread.sleep(6000);
                    // o.wait();
                    System.out.println(System.currentTimeMillis() - begin);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (o) {
                System.out.println("...");
            }
        }).start();
    }
}

相關文章