wait&sleep
- wait释放锁,sleep不释放
- wait是Object的方法,sleep是线程的静态方法
- wait需要和synchronized一起使用
- wait和sleep之后,线程都处于TIME-WAITING状态
- wait的线程处于与当前锁对象相关的waitset中
- wait和sleep被Interrupte都会有InterruptedException
notify
- obj.notify()随机叫醒一个与obj对象锁相关的waitset中的一个线程
- obj.notifyAll()唤醒所有与obj对象锁相关的waitset中的线程
正确使用姿势
package com.leolee.multithreadProgramming.concurrent.waitAndNotify;
import lombok.extern.slf4j.Slf4j;
/**
* @ClassName Test
* @Description: wait 和 notify测试
* @Author LeoLee
* @Date 2020/12/2
* @Version V1.0
**/
@Slf4j
public class Test {
public final static Object obj = new Object();
public static boolean isCigarette = false;
public static boolean isFood = false;
/*
* 功能描述: <br>
* 〈wait notify的正确用法〉
* @Param: []
* @Return: void
* @Author: LeoLee
* @Date: 2020/12/2 16:10
*/
public void rightWay() throws InterruptedException {
new Thread(() -> {
synchronized (obj) {
log.info("{}开始写代码...", Thread.currentThread().getName());
while (!isCigarette) {
try {
log.info("{}没烟写不下去休息去了...", Thread.currentThread().getName());
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (isCigarette) {
log.info("{}抽完烟继续写代码...", Thread.currentThread().getName());
} else {
log.info("{}被叫醒之后发现还是没烟心态崩了,回家了...", Thread.currentThread().getName());
}
}
}, "张三").start();
new Thread(() -> {
synchronized (obj) {
log.info("{}开始写代码...", Thread.currentThread().getName());
while (!isFood) {
try {
log.info("{}没外卖写不下去休息去了...", Thread.currentThread().getName());
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (isFood) {
log.info("{}吃上外卖继续写代码...", Thread.currentThread().getName());
} else {
log.info("{}被叫醒之后发现还是没外卖心态崩了,回家了...", Thread.currentThread().getName());
}
}
}, "李四").start();
Thread.sleep(2500);
new Thread(() -> {
synchronized (obj) {
log.info("{}来送外卖了...", Thread.currentThread().getName());
isFood = true;
obj.notifyAll();
}
}, "王五").start();
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
test.rightWay();
}
}
执行结果:
16:18:52.770 [张三] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 张三开始写代码...
16:18:52.789 [张三] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 张三没烟写不下去休息去了...
16:18:52.790 [李四] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 李四开始写代码...
16:18:52.790 [李四] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 李四没外卖写不下去休息去了...
16:18:55.272 [王五] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 王五来送外卖了...
16:18:55.272 [李四] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 李四继续写代码...
16:18:55.272 [张三] INFO com.leolee.multithreadProgramming.concurrent.waitAndNotify.Test - 张三没烟写不下去休息去了...