Java多线程____生产者与消费者模型
1.仓库类__:入库和出库的集合 有生产和出货方法
package com.test.thread;
import java.util.LinkedList;
/**
* @author Administrator
* 仓库类
*/
public class Storage {
//存储集合
private LinkedList<Object> list = new LinkedList<Object>();
public void ruku(int num) {
synchronized (list) {
while (list.size() + num > 100) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= num; ++i) {
list.add(new Object());
}
System.out.println("生产完成量为:" + num + "现仓库有数量为:" + list.size());
list.notifyAll();
}
}
public void chuku(int num) {
synchronized (list) {
while (list.size() < num) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= num; ++i) {
list.remove();
}
System.out.println("取货量为:" + num + "仓库剩余量为:" + list.size());
list.notifyAll();
}
}
}
2.生产者
package com.test.thread;
/**
* @author Administrator
* 生产类
*/
public class Producer extends Thread {
//每次生产的数量默认为仓库最大容量
private int num=100;
//建立仓库
private Storage storage;
// get/set方法
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Storage getStorage() {
return storage;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
//构造函数,设置仓库
public Producer(Storage storage) {
this.storage = storage;
}
//线程run方法执行生产方法
public void produce(int num) {
storage.ruku(num);
}
@Override
public void run() {
produce(num);
}
}
3.消费者
package com.test.thread;
/**
* @author Administrator
* 消费类
*/
public class Consumer extends Thread {
// 每次消费的产品数量
private int num;
// 所在放置的仓库
private Storage storage;
// 构造函数,设置仓库
public Consumer(Storage storage) {
this.storage = storage;
}
// get/set方法
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Storage getStorage() {
return storage;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
//先run方法执行消费方法
public void consume(int num) {
storage.chuku(num);
}
@Override
public void run() {
consume(num);
}
}
4.测试类
package com.test.thread;
import java.util.Random;
public class Test {
public static void main(String[] args) {
//仓库
Storage storage = new Storage();
//生产类
Producer p1 = new Producer(storage);
//客户类
Consumer c1 = new Consumer(storage);
Consumer c2 = new Consumer(storage);
Consumer c3 = new Consumer(storage);
//要生产的数量
p1.setNum(100);
//消费的数量随机的
c1.setNum(new Random().nextInt(20));
c2.setNum(new Random().nextInt(20));
c3.setNum(new Random().nextInt(20));
//线程开始执行
p1.start();
c1.start();
c2.start();
c3.start();
}
}
//运行结果