咱们从一个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)后能力继续执行业务逻辑。
发表回复