wait、notify、notifyAll

  这三个方法都是属于Object的,Java中的类默认继承Object,所以在任何方法中都可以直接调用wait(),notifyAll(),notify(),static方法也一样,new一个对象再调用。这三个方法必须是在获取到monitor锁的前提下使用,也就是使用ReentrantLock这类锁是不行的,只能是synchronized关键字内部,否则会出现IllegalMonitorStateException异常。

1、wait:

  作用就是进入阻塞状态,准确的说是Waiting状态,如果调用的wait(timeout),进入Timed-Waiting状态,并且会释放monitor锁。

调用wait()有四种被唤醒方式:

  1).notify

  2).notifyAll

  3).wait(timeout)

  4).interrupt()

  这几种方式我们都比较熟悉,无论你开发过程中有没有用过多线程,提一下interrupt(),因为无论是调用sleep、wait、join等进入阻塞状态下,都是可以通过抛出异常响应中断。

基本使用:证明wait()会释放monitor锁

public class ThreadClass {

    private Object object = new Object();

    public static void main(String[] args) throws InterruptedException{
        ThreadClass threadClass = new ThreadClass();
        Thread thread = new Thread(threadClass.new Thread1());
        Thread thread1= new Thread(threadClass.new Thread2());
        thread.start();
        Thread.sleep(100);
        thread1.start();
    }

    class Thread1 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                try {
                    System.out.println(Thread.currentThread().getName() + "获取到lock");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "继续执行");
            }
        }
    }

    class Thread2 implements Runnable{
        @Override
        public void run() {
            synchronized (object) {
                object.notify();
                System.out.println(Thread.currentThread().getName() + "调用了notify");
            }
        }
    }
}
代码实现

相关文章: