首先先看代码
这个是网上流传比较广的例子
/**
* Created by Jarvis.y on 2020/11/4
* <p>
* 1、wait() and notify() and notifyAll() 需要在 synchronized 同步方法中。
* 如果没有 synchronized,会出现 IllegalMonitorStateException 异常
* 2、wait and notify 一定要使用被锁的对象(synchronized修饰的)。
* 3、使用wait的时候 一定要使用while 循环而不是if判断
*/
public class WaitNotifyThread {
public static void main(String[] args) {
List<Integer> container = new ArrayList<>();
Thread producer = new Thread(new Producer(container));
Thread consumer = new Thread(new Consumer(container));
Thread consumer1 = new Thread(new Consumer(container));
producer.start();
consumer.start();
consumer1.start();
}
}
class Producer implements Runnable {
/**
* 产品容器
*/
private final List<Integer> container;
public Producer(List<Integer> container) {
this.container = container;
}
/**
* 生产者生产方法
*
* @throws InterruptedException
*/
private void produce() throws InterruptedException {
//产品容器容量
int capacity = 5;
synchronized (container) {
//当容器已满,暂停生产
while (container.size() == capacity) {
System.out.println("...容器已经满了,暂停生产...");
container.wait();
}
Random random = new Random();
int p = random.nextInt(50);
//模拟1秒生产一个产品
TimeUnit.MILLISECONDS.sleep(500);
System.out.println("生产产品:" + p);
container.add(p);
container.notifyAll();
}
}
@Override
public void run() {
while (true) {
try {
produce();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("produce error");
}
}
}
}
class Consumer implements Runnable {
/**
* 产品容器
*/
private final List<Integer> container;
public Consumer(List<Integer> container) {
this.container = container;
}
/**
* 消费者消费产品
*/
private void consume() throws InterruptedException {
synchronized (container) {
while (container.isEmpty()) {
System.out.println("...容器是空的,暂停消费...");
container.wait();
}
Integer p = container.remove(0);
//模拟1秒消费一个产品
TimeUnit.MILLISECONDS.sleep(500);
System.out.println("消费产品:" + p);
container.notifyAll();
}
}
@Override
public void run() {
while (true) {
try {
consume();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("consume error");
}
}
}
}
首先:
1、wait() and notify() and notifyAll() 需要在 synchronized 同步方法中。
如果没有synchronized 修饰的Java虚拟机会生成 IllegalMonitorStateException。
要保证多个线程操作同一个对象的时候每次只能一个线程操作。
2、wait and notify 一定要使用被锁的对象(synchronized修饰的)。
这个没啥解释的。因为释放锁或者唤醒线程等待锁,都是需要同一个对象。
3、使用wait的时候 一定要使用while 循环而不是if判断
这个我纠结了很久才想明白,原因是因为之前只用了一个生产者线程,一个消费者线程。这样用if判断可能也没有问题。
如果使用两个消费者线程的话就可能会出问题
首先生产者线程p(一下都为p) 生产一个任务。消费者c1 去消费一个任务。然后c2线程执行发现没有任务就会wait等待,唤醒其他线程,这个时候p再生产一个任务,然后c1执行把这个任务消费掉,消费完后会唤醒所有线程,这个时候如果唤醒了c2线程,如果是if判断的话就会直接往下走,去执行消费任务,然而时候队列并没有任务,所以会消费失败。