您的位置:首页 > 职场人生

JAVA多线程之——经典面试消费者与生产者

2017-03-26 15:23 381 查看
用wait与notify、notifyAll 实现生产者与消费者

关于多线程的生产者与消费者有多种方式实现。目前用学过的wait、notifyAll来实现。代码:

public class ThreadTest6 {
static class Storehouse {
private int capacity; // 仓库的容量
private int size; // 仓库的存货量

/**
* 初始化仓库的容量和实际存货量
*
* @param capacity
* @param size
*/
public Storehouse(int capacity, int size) {
super();
this.capacity = capacity;
this.size = size;
}

/**
* 生产指定数量的产品
*
* @param count
*            生产的产品数量
*/
public synchronized void product(int count) {
try {
while (count > 0 ) {
if (size >= capacity) {
wait();
} else {
// 计算生产数量 如果生产的数量和现有的数量大于总容量,则生产量为总容量 - 当前容量 否则 生产需要的容量。
int inc = (count + size) > capacity ? capacity - size
: count;
size += inc;
count -= inc;
System.out.println("本次生产产品:" + inc + "个,当前总产品:" + size
+ "个");
}
notifyAll();
}
} catch (InterruptedException e) {
}
}

/**
* 消费制定的产品数量
*
* @param count
*            消费指定的产品数量。
*/
public synchronized void consume(int count) {
try {
while (count > 0) {
if (size <= 0) {
wait();
} else {
// 消费产品 如果消费的产品比剩余产品多,就消费掉所有剩余产品。否则就消费需要的产品量
int inc = count > size ? size : count;
size -= inc;
count -= inc;
System.out.println("本次消费产品:" + inc + "个,当前总产品:" + size
+ "个");

}
notifyAll();
}

} catch (InterruptedException e) {
}
}
}

static class Cusomer{
private Storehouse storehouse;

public Cusomer(Storehouse storehouse) {
super();
this.storehouse = storehouse;
}

public void consume(final int count) {

new Thread(new Runnable() {
@Override
public void run() {
storehouse.consume(count);
}
},"消费者").start();

}
}

static class Producer{
private Storehouse storehouse;

public Producer(Storehouse storehouse) {
super();
this.storehouse = storehouse;
}

public void product(final int count) {

new Thread(new Runnable() {
@Override
public void run() {
storehouse.product(count);
}
},"消费者").start();

}
}

public static void main(String[] args) {
Storehouse storehouse = new Storehouse(100, 0);
Cusomer cusomer = new Cusomer(storehouse);
Producer producer = new Producer(storehouse);

cusomer.consume(10);
producer.product(110);
cusomer.consume(50);
cusomer.consume(70);
cusomer.consume(20);
cusomer.consume(100);
producer.product(60);
producer.product(10);
producer.product(510);

}

}


运行结果:

本次生产产品:100个,当前总产品:100个
本次消费产品:70个,当前总产品:30个
本次消费产品:10个,当前总产品:20个
本次生产产品:10个,当前总产品:30个
本次消费产品:20个,当前总产品:10个
本次生产产品:10个,当前总产品:20个
本次生产产品:80个,当前总产品:100个
本次消费产品:50个,当前总产品:50个
本次生产产品:50个,当前总产品:100个
本次消费产品:100个,当前总产品:0个
本次生产产品:100个,当前总产品:100个
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 多线程 面试