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

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 ...
(程序一直停在此处....)
相信聪明的你已经懂了吧.....
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。