关于java:Object中的wait和notify方法详解

29次阅读

共计 1935 个字符,预计需要花费 5 分钟才能阅读完成。

咱们从一个 IllegalMonitorStateException 的解决来开始咱们的解说。
小 A 写的代码抛出了 java.lang.IllegalMonitorStateException 异样信息。

public class WaitDemo {public static void main(String[] args) throws Exception  {Object o = new Object();
        o.wait();
        // 业务逻辑代码
    }
}

小 A 通过查看源码,确认了抛出 IllegalMonitorStateException 异样是因为调用 wait 办法的时以后线程没有获取到调用对象的锁。

Throws:IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor.

依据谬误起因,将代码改成如下,业务代码失常运行。

public class WaitDemo {public static void main(String[] args) throws Exception  {Object o = new Object();
        synchronized (o){o.wait();
        }
        // 业务逻辑代码
    }
}

通过这个异样的解决小 A 意识到本人对于 wait 和 notify 办法不足足够的理解,导致了异样的产生,上面咱们一起来学习下 wait 和 notify 办法

wait 和 notify 办法介绍

wait 和 notify 是 Object 类中定义的办法。调用这两个办法的前提条件:以后线程领有调用者的锁。

wait 办法有好几个重载办法,但最终都调用了如下的 wait 本地办法。调用 wait 办法后,以后线程会进入 waiting 状态直到其余线程调用此对象的 notify、notifyAll 办法或者指定的等待时间过来。

public final native void wait(long timeout) throws InterruptedException;

notify 和 notifyAll 办法, 两者的区别是 notify 办法唤醒一个期待在调用对象上的线程,notifyAll 办法唤醒所有的期待在调用对象上的线程。

那么唤醒后的线程是否就能够间接执行了?答案是否定的。唤醒后的线程须要获取到调用对象的锁后能力继续执行。

public final native void notify();
public final native void notifyAll();

应用场景和代码样例

wait 和 notify 办法能够在多线程的告诉场景下应用,比方对于共享变量 count,写线程和读线程交替的写和读。如上面代码所示。

package org.example;

public class WaitDemo {
    private static int count = 0;
    private static Object o = new Object();
    public static void main(String[] args) throws InterruptedException {Write w = new Write();
        Read r = new Read();
        w.start();
        // 为了保障写线程先获取到对象锁
        Thread.sleep(1000);
        r.start();}
    static class Write extends Thread{
        @Override
        public void run(){while(true){synchronized (o){o.notify();
                    count++;
                    try {Thread.sleep(100);
                        o.wait();} catch (InterruptedException e) {e.printStackTrace();
                    }
                }
            }

        }
    }

    static class Read extends Thread{
        @Override
        public void run(){while(true){synchronized (o){System.out.println(count);
                    o.notify();
                    try {Thread.sleep(100);
                        o.wait();} catch (InterruptedException e) {e.printStackTrace();
                    }
                }
            }

        }

    }
}

运行以上代码后果如下图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

合乎咱们的预期,依照程序输入了 count 的值。

总结

应用 wait 和 notify 办法有以下留神点

  • 调用 wait 和 notify 办法时须要获取到调用对象的锁(monitor)。
  • 调用 wait 办法后,以后线程进入 waitting 状态并开释锁。
  • 期待线程被 notify 唤醒后,须要或者到调用对象的锁(monitor)后能力继续执行业务逻辑。

正文完
 0