sleep与wait区别

【死记硬背】

1 对于 sleep()方法,我们首先要知道该方法是属于 Thread 类中的。而 wait()方法,则是属于 Object 类中的。

2 sleep()方法导致了程序暂停执行指定的时间,让出cpu给其他线程,但是他的监控状态依然保持着,当指定的时间到了又会自动恢复运行状态。

3 在调用 sleep()方法的过程中,线程不会释放对象锁。

4 当调用 wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用 notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。

【答案解析】

wait()方法使用Demo:

import java.util.concurrent.TimeUnit;public class WaitNotifyTest {    public static void main(String[] args) {        ThreadA t1 = new ThreadA("t1");        synchronized (t1){            try{                // 启动“线程t1”                System.out.println(Thread.currentThread().getName()+" start t1");                t1.start();                // 主线程等待t1通过notify()唤醒。                System.out.println(Thread.currentThread().getName()+" wait()");                //t1.wait();                t1.wait(2000);                System.out.println(Thread.currentThread().getName()+" continue");            }catch (InterruptedException e){                e.printStackTrace();            }        }    }    static class ThreadA extends Thread{        public ThreadA(String name) {            super(name);        }        public void run(){            synchronized (this) {                System.out.println(Thread.currentThread().getName()+" call notify()");                try {                    TimeUnit.SECONDS.sleep(1);                } catch (InterruptedException e) {                    e.printStackTrace();                }                // 唤醒当前的wait线程                notify();            }        }    }}

sleep()方法使用Demo:

public class SleepTest extends Thread{    @Override    public void run(){        System.out.println("thread run...");    }    public static void main(String[] args) throws Exception{        Thread thread = new SleepTest();        thread.start();        // 休眠1秒        Thread.sleep(1000);        System.out.println("执行over...");    }}

【温馨提示】

点赞+收藏文章,关注我并私信回复【面试题解析】,即可100%免费领取楼主的所有面试题资料!

(0)
小多多的头像小多多创始人

相关推荐

发表回复

登录后才能评论