缓冲池法
通过缓冲池实现
生产者类
class Producer01 implements Runnable{
Store01 store;//定义一个store类
Producer01(Store01 store){//构造方法
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {//循环100次
store.into();//生产放入
System.out.println("生产了第"+i+"个");
}
}
}
消费者类
class Consumer01 implements Runnable{
Store01 store;//定义一个store类
Consumer01(Store01 store){//构造方法
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {//循环100次
store.remove();//消费取出
System.out.println("消费了第"+i+"个");
}
}
}
缓冲池类
class Store01{
private final static int MAX=10;//上限
private static int stock=0;//目前库存
public synchronized void into() {//放入,同步方法
if (stock==MAX){
try {
this.wait();//满库存,等待
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("库存已满,等待消费");
}
stock++;//生产物品
this.notifyAll();//唤醒线程
}
public synchronized void remove() {//取出
if (stock==0){
try {
this.wait();//零库存,等待
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("没有库存,等待生产");
}
stock--;//消费物品
this.notifyAll();//唤醒线程
}
}
Main方法
public static void main(String[] args) {
Store01 store = new Store01();
Producer01 producer = new Producer01(store);
Consumer01 consumer = new Consumer01(store);
new Thread(producer).start();
new Thread(consumer).start();
}
标志位法
生产者类
class Producer02 implements Runnable{
Store02 store;//定义一个store类
Producer02(Store02 store){//构造方法
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {//循环100次
store.into();//生产放入
System.out.println("生产了第"+i+"个");
}
}
}
消费者类
class Consumer02 implements Runnable{
Store02 store;//定义一个store类
Consumer02(Store02 store){//构造方法
this.store=store;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {//循环100次
store.remove();//消费取出
System.out.println("消费了第"+i+"个");
}
}
}
标志位实现类
class Store02 {
private boolean flag=false;
public synchronized void into() {//放入,同步方法
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("已生产,等待消费");
this.flag=!this.flag;
this.notifyAll();//唤醒线程
}
public synchronized void remove() {//取出
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费完成,等待生产");
this.flag=!this.flag;
this.notifyAll();//唤醒线程
}
}
Main方法
public static void main(String[] args) {
Store02 store02 = new Store02();
Producer02 producer02 = new Producer02(store02);
Consumer02 consumer02 = new Consumer02(store02);
new Thread(producer02).start();
new Thread(consumer02).start();
}