Java学习:线程类简单应用(生产者消费者模型)
设有一个最大库存为5的小书橱(有界缓冲池),每次有一批书要入库(生产),同时会有一定读者对书库的书购买(消费).
使用synchronized
关键字的同步方法避免丢失修改的情况.
图解:
结果:
最大库存为5小书库已构建!
图书入库:小书库,当前库存:1
图书入库:小书库,当前库存:2
图书入库:小书库,当前库存:3
图书入库:小书库,当前库存:4
图书入库:小书库,当前库存:5
图书出库:小书库,当前库存:4
图书出库:小书库,当前库存:3
图书出库:小书库,当前库存:2
图书出库:小书库,当前库存:1
图书出库:小书库,当前库存:0
代码:
// 测试类
public class TestLittleLibrary {
public static void main(String[] args) {
LittleLibrary library = new LittleLibrary("小书库",5);// 库存5的小书橱
System.out.println("最大库存为" + library.getSIZE() + library.getName() + "已构建!");
Booker booker = new Booker(library);// 生产者
Reader reader = new Reader(library);// 消费者
booker.start();
reader.start();
}
}
// 作为缓冲池的库类
public class LittleLibrary {
private String name;// 书名
private int SIZE;// 最大库存
private int num;// 当前库存量
public LittleLibrary(String name, int size) {
this.name = name;
this.SIZE = size;
}
// 同步的入库(生产)方法
public synchronized void input() {
// 若当前库存量为最大库存量,进入等待直到被通知唤醒
while (num == SIZE) {
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println("图书入库:" + getName() + ",当前库存:" + num);
notifyAll();// 通知出库(消费)
}
// 同步的出库(消费)方法
public synchronized void output() {
// 若库中无书,则进入等待直到被通知唤醒
while (num == 0) {
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
num--;
System.out.println("图书出库:" + getName() + ",当前库存:" + num);
notifyAll();// 通知入库(生产)
}
public String getName() {
return name;
}
public int getSIZE() {
return SIZE;
}
}
// 生产者线程
public class Booker extends Thread {
LittleLibrary library;
public Booker(LittleLibrary library) {
this.library = library;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
library.input();// 调用同步入库方法
}
}
}
// 消费者线程
public class Reader extends Thread {
LittleLibrary library;
public Reader(LittleLibrary library) {
this.library = library;
}
@Override
public void run() {
for (int i = 0; i < 10; i ++) {
library.output();// 调用同步消费方法
}
}
}