美文网首页
夜深了,快睡吧-sleep()和wait()区别

夜深了,快睡吧-sleep()和wait()区别

作者: 一个喜欢烧砖的人 | 来源:发表于2018-07-30 23:07 被阅读72次
    sleep():
    • 属于Thread类
    • sleep()方法导致了程序暂停执行指定的时间,让出cpu去其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态
    • 在调用sleep()方法的过程中,线程不会释放对象锁
    wait():
    • 属于object的方法
    • 调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备

    废话不多说,直接撸代码

    public class mySleepTest {
        public static void main(String[] args) {
            new Thread(new Thread1()).start();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(new Thread2()).start();
        }
    
        public static class Thread1 implements Runnable {
    
            public void run() {
                synchronized (mySleepTest.class) {
                    System.out.println("enter thread 1 .....");
                    System.out.println("thread1 is wairting....");
                    try {
                        mySleepTest.class.wait();
                    } catch (Exception e) {
    
                    }
                    System.out.println("thread1 is going on ...");
                    System.out.println("thread1 is over");
                }
            }
        }
    
        public static class Thread2 implements Runnable {
    
            public void run() {
                synchronized (mySleepTest.class) {
                    System.out.println("enter thread 2 ...");
                    System.out.println("thread 2 is sleeping ...");
                    mySleepTest.class.notify();
    
                    try {
                        Thread.sleep(5000);
                    } catch (Exception e) {
    
                    }
                    System.out.println("thread 2 is going on ...");
                    System.out.println("thread 2 is over ...");
                }
            }
        }
    }
    
    

    运行结果

    enter thread 1 .....
    thread1 is wairting....
    enter thread 2 ...
    thread 2 is sleeping ...
    thread 2 is going on ...
    thread 2 is over ...
    thread1 is going on ...
    thread1 is over
    Process finished with exit code 0
    

    注释掉 mySleepTest.class.notify();
    运行结果:

    enter thread 1 .....
    thread1 is wairting....
    enter thread 2 ...
    thread 2 is sleeping ...
    thread 2 is going on ...
    thread 2 is over ...
    (程序一直停在此处....)
    
    相信聪明的你已经懂了吧.....

    相关文章

      网友评论

          本文标题:夜深了,快睡吧-sleep()和wait()区别

          本文链接:https://www.haomeiwen.com/subject/ndiqvftx.html