package com.learning.wait;
/**
* @Author wangyouhui
* @Description 对象的wait方法必须放synchronized代码块里
**/
public class WaitLearning {
static final Object lock = new Object();
public static void main(String[] args) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at com.learning.wait.WaitLearning.main(WaitLearning.java:11)
3.在synchronized代码块中执行等待,获得锁的主线程一直在等待,阻塞中
package com.learning.wait;
/**
* @Author wangyouhui
* @Description 对象的wait方法必须放synchronized代码块里
**/
public class WaitLearning {
static final Object lock = new Object();
public static void main(String[] args) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4.wait(时间),当超过等待时间会自动唤醒
package com.learning.wait;
import lombok.extern.slf4j.Slf4j;
/**
* @Author wangyouhui
* @Description 对象的wait时间方法,当时间过去后,会继续执行
**/
@Slf4j
public class WaitTimeLearning {
static final Object lock = new Object();
public static void main(String[] args) {
new Thread(()->{
synchronized (lock) {
try {
log.info("线程1等待");
lock.wait(2000);
log.info("线程1继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "thread1").start();
}
}
5.wait(时间),等待时间内被其它线程唤醒会提前唤醒
package com.learning.wait;
import lombok.extern.slf4j.Slf4j;
/**
* @Author wangyouhui
* @Description 对象的wait时间方法,当时间过去后,会继续执行
**/
@Slf4j
public class WaitTimeLearning2 {
static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
synchronized (lock) {
try {
log.info("线程1等待");
lock.wait(2000);
log.info("线程1继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "thread1").start();
Thread.sleep(1000);
synchronized (lock){
log.info("主线程唤醒");
lock.notify();
}
}
}
[thread1] INFO com.learning.notify.NotifyLearning - 线程1等待
[thread2] INFO com.learning.notify.NotifyLearning - 线程2等待
[main] INFO com.learning.notify.NotifyLearning - 主线程拿到锁,执行lock.notify方法,唤醒waitset中的一个线程
[thread1] INFO com.learning.notify.NotifyLearning - 线程1继续执行
[thread1] INFO com.learning.notifyall.NotifyAllLearning - 线程1等待
[thread2] INFO com.learning.notifyall.NotifyAllLearning - 线程2等待
[main] INFO com.learning.notifyall.NotifyAllLearning - 主线程拿到锁,执行lock.notify方法,唤醒waitset中的一个线程
[thread2] INFO com.learning.notifyall.NotifyAllLearning - 线程2继续执行
[thread1] INFO com.learning.notifyall.NotifyAllLearning - 线程1继续执行