sleep()和wait()有什么区别?

sleep就是正在执行的线程主动让出cpu,cpu去执行其余线程,在sleep指定的时间事后,cpu才会回到这个线程上继续往下执行,若是当前线程进入了同步锁,sleep方法并不会释放锁,即便当前线程使用sleep方法让出了cpu,但其余被同步锁挡住了的线程也没法获得执行。ide

wait是指在一个已经进入了同步锁的线程内让本身暂时让出同步锁,以便其余正在等待此锁的线程能够获得同步锁并运行,只有其余线程调用了notify方法notify并不释放锁,只是告诉调用过wait方法的线程能够去参与得到锁的竞争了,但不是立刻获得锁,由于锁还在别人手里,别人还没释放。若是notify方法后面的代码还有不少,须要这些代码执行完后才会释放锁,能够在notfiy方法后增长一个等待和一些代码,看看效果,调用wait方法的线程就会解除wait状态和程序能够再次获得锁后继续向下运行。对于wait的讲解必定要配合例子代码来讲明,才显得本身真明白。this

public class MultiThread {
    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Thread2()).start();
    }
private static class Thread1 implements Runnable {
        @Override
        public void run() {
            // 因为这里的Thread1和下面的Thread2内部run方法要用同一对象做为监视器,咱们这里不能用this,由于在Thread2里面的this和这个Thread1的this不是同一个对象。咱们用MultiThread.class这个字节码对象,当前虚拟机里引用这个变量时,指向的都是同一个对象。
            synchronized (MultiThread.class) {
                System.out.println("enter thread1...");
                System.out.println("thread1 is waiting");
                try {
                    // 释放锁有两种方式,第一种方式是程序天然离开监视器的范围,也就是离开了synchronized关键字管辖的代码范围,另外一种方式就是在synchronized关键字管辖的代码内部调用监视器对象的wait方法。这里,使用wait方法释放锁。
                    MultiThread.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread1 is being over!");
            }
        }
    }
private static class Thread2 implements Runnable {
        @Override
        public void run() {
            synchronized (MultiThread.class) {
                System.out.println("enter thread2...");
                System.out
                        .println("thread2 notify other thread can release wait status..");
                // 因为notify方法并不释放锁,即便thread2调用下面的sleep方法休息了10毫秒,但thread1仍然不会执行,由于thread2没有释放锁,因此Thread1没法得不到锁。
                MultiThread.class.notify();
                System.out.println("thread2 is sleeping ten millisecond...");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2 is being over!");
            }
        }
    }
}

结果:
enter thread1...
thread1 is waiting
enter thread2...
thread2 notify other thread can release wait status..
thread2 is sleeping ten millisecond...
thread2 is being over!
thread1 is being over!
相关文章
相关标签/搜索