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

2018-07-30  本文已影响72人  一个喜欢烧砖的人
sleep():
wait():

废话不多说,直接撸代码

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 ...
(程序一直停在此处....)
相信聪明的你已经懂了吧.....
上一篇 下一篇

猜你喜欢

热点阅读