发布于 5年前

Object.wait()与Thread.sleep()的区别

Object.wait()方法

Object.wait()与Object.notify(),Object.nofityAll()需要搭配使用,协作线程之间的通信。

线程获取到对象锁后,当它调用锁的wait()方法,就会释放对象锁,同时线程挂起,直到其他线程获取到对象锁并执行notify()后,线程重新开始运行。

示例

final static Object lock = new Object();
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("thread a get lock");
                    try {
                        System.out.println("thread a start wait");
                        lock.wait();
                        System.out.println("thread a end wait");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    System.out.println("thread b get lock");
                    System.out.println("thread b notify lock");
                    lock.notify();
                }
            }
        }).start();
    }

输出:

thread a get lock
thread a start wait
thread b get lock
thread b notify lock
thread a end wait

Thread.sleep()方法

线程获取到对象锁之后,调用Thread.sleep()时不会释放线程所占有的对象锁,其他线程也不能获取被此线程占用对象锁。直到线程sleep结束,其他线程才能获取到对象锁。

示例

final static Object lock = new Object();
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("thread a get lock");
                    try {
                        System.out.println("thread a start sleep");
                        Thread.sleep(1000);
                        System.out.println("thread a end sleep");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("thread b get lock");
                    System.out.println("thread b notify lock");
                    lock.notify();
                }
            }
        }).start();
    }

输出:

thread a get lock
thread a start sleep
thread a end sleep
thread b get lock
thread b notify lock
©2020 edoou.com   京ICP备16001874号-3