sleep和wait的区别

2019-08-13  本文已影响0人  叫我胖虎大人

基本差别

最主要的本质区别

代码演示

示例1

public class CycleWait implements Runnable{

    private String value;

    @Override
    public void run() {
        try{
            Thread.sleep(5000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        value = "We have data now";
    }

    public static void main(String[] args) throws InterruptedException {


        CycleWait cycleWait = new CycleWait();
        Thread t = new Thread(cycleWait);
        t.start();
        System.out.println("Value : " + cycleWait.value);
        //主线程的等待方
        while (cycleWait.value == null){
            Thread.sleep(100);
        }
        System.out.println("Value : " + cycleWait.value);
    }
}

运行结果

Value : null
Value : We have data now

Value在线程t休眠5秒之后才完成赋值操作


示例2

package com.mmall.concurrency.thread;

public class WaitSleepDemo {

    public static void main(String[] args) {
        final Object lock = new Object();
        new Thread(() -> {
            try {
                System.out.println("Thread A is waiting to get lock");
                synchronized (lock){
                    System.out.println("Thread A get lock");
                    Thread.sleep(20);
                    System.out.println("Thread A do wait method ");
                    //线程A释放锁
                    lock.wait();
                    System.out.println("Thread A is done ---");
                }
            }catch (InterruptedException e ){
                e.printStackTrace();
            }
        }).start();

        //设置成2000,线程A的wait操作释放锁之后,主线程等待,并没有进入线程B,这个时候还是线程A先完成工作
        try{
            Thread.sleep(20);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        new Thread(() -> {
            try {
                System.out.println("Thread B is waiting to get lock");
                synchronized (lock){
                    System.out.println("Thread B get lock");
                    Thread.sleep(20);
                    lock.notifyAll();
                    System.out.println("Thread B is done ---");
                }
            }catch (InterruptedException e ){
                e.printStackTrace();
            }
        }).start();
    }
}

关于notify
运行结果

Thread A is waiting to get lock
Thread A get lock
Thread A do wait method
Thread B is waiting to get lock
Thread B get lock
Thread B is done ---
Thread A is done ---

上一篇下一篇

猜你喜欢

热点阅读