等待唤醒机制与简单的生产消费者模型
/*
简单的生产消费者模型
*/
import java.lang.Thread;
import java.lang.Runnable;
class ThreadDemo4 {
public static void main(String[] args) {
Res res = new Res(); //资源为被操作的共享数据,类型为对象
new Thread(new Producer(res)).start();
new Thread(new Customer(res)).start();
}
}
class Res {
public int num;
}
class Producer implements Runnable {
private Res res;
Producer (Res res) { //为了操作共享数据,在构造函数中就赋值给它
this.res = res;
}
public void run () {
while (true) {
//res对象在对内存中唯一,所以生产者消费者持有的锁都是res
synchronized (res) {
System.out.println("开始生产!");
//如果库存大于99,那么停止生产,wait该线程,释放持有的锁,释放执行权,等待被唤醒
if (res.num > 99) {
System.out.println("库存已满,停止生产,请立即消费!");
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 如果库存没满,那么继续生产,并唤醒可能刚刚消费完所有库存,正在wait的消费者线程
res.num++;
System.out.println("完成生产" + "..." + "当前库存为" + res.num);
res.notify();
}
}
}
}
}
class Customer implements Runnable {
private Res res;
Customer (Res res) { //为了操作共享数据,在构造函数中就赋值给它
this.res = res;
}
public void run () {
while (true) {
//res对象在对内存中唯一,所以生产者消费者持有的锁都是res
synchronized (res) {
System.out.println("开始消费!");
//如果库存小于1,那么停止消费,wait该线程,释放持有的锁,释放执行权,等待被唤醒
if (res.num < 1 ) {
System.out.println("库存已空,停止消费,请立即生产!");
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//如果库存没空,那么继续消费,并唤醒可能刚刚将库存存满,正在wait的生产者线程
res.num--;
System.out.println("消费了" + "..." + "当前库存为" + res.num);
res.notify();
}
}
}
}
}