notify() 唤醒一个进程
wait() 阻塞一个进程
synchronized 同步锁,修饰代码块和方法均可
wait和notify必须在synchronized块中,否则会抛出IllegalMonitorStateException
/**
* 要求 缓存区满后生产者不能生产,缓存区空后消费者不再消费,缓存区不满不空消费者可以消费,生产者可以生产
*
* ProducerAndCustomer类 count记录缓冲区有几个物品 ;producerAndCustomer它是实例负责被两个线程类调用
* 最开始想的是线程run方法单独写,失败了。但要实现线程通信需要线程之间共享一个缓冲区
* 注意的一点是while循环需要放在synchronized外面,不然只能同步,不能异步。
* 最好另设一个类带替代ProducerAndCustomer的共享作用
*
* 2022-06-14 15:22
*/
class Producer extends Thread {
ProducerAndCustomer producerAndCustomer;
Producer(ProducerAndCustomer producerAndCustomer){
this.producerAndCustomer = producerAndCustomer;
}
@Override
public void run() {
while (true){
producerAndCustomer.product(getName());
}
}
}
class Consumer extends Thread {
ProducerAndCustomer producerAndCustomer;
Consumer(ProducerAndCustomer producerAndCustomer){
this.producerAndCustomer = producerAndCustomer;
}
@Override
public void run() {
while (true){
producerAndCustomer.consume(getName());
}
}
}
public class ProducerAndCustomer {
private int count = 0;
static ProducerAndCustomer producerAndCustomer = new ProducerAndCustomer();
public static void main(String[] args) {
new Producer(producerAndCustomer).start();
new Consumer(producerAndCustomer).start();
}
synchronized void product(String name) {
if (count > 20) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(name + "生产第" + count + "个产品");
count++;
notify();
}
synchronized void consume(String name) {
if (count <= 0) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(name + "消费第" + count + "个产品");
count--;
notify();
}
}