/**
* @author Sun 生产者消费者模型
*/
public class MultiThreading {
public MultiThreading() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Store s = new Store(5);// 初始化仓库容量为5
// 创建生产者和消费者
Thread pro1 = new Producer(s);
Thread pro2 = new Producer(s);
Thread pro3 = new Producer(s);
Thread con1 = new Consumer(s);
Thread con2 = new Consumer(s);
Thread con3 = new Consumer(s);
// 启动线程
pro1.start();
pro2.start();
pro3.start();
con1.start();
con2.start();
con3.start();
}
}
/**
* @author Sun 仓库类
*/
class Store {
private final int MAX_SIZE;// 仓库的最大容量
private int cur_count;// 当前的货物数量
public Store(int n) {
// TODO Auto-generated constructor stub
MAX_SIZE = n;
cur_count = 0;
}
/**
* 向仓库中添加货物的方法
*/
public
synchronized void add() {
while (cur_count >= MAX_SIZE) {
// 判断仓库是否已经满了
System.out.println("已经满了!");
try {
// 这个this指针到底指向Store对象,阻塞了拥有锁的线程,并释放了对锁的占有
this.wait();// 阻塞线程
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
++cur_count;// 添加成功则数量加一
// 打印当前仓库中的货物数量
System.out.println(Thread.currentThread().toString()
+ " put ,current count:" + cur_count);
// 唤醒堵塞的消费者线程前来取货,消费者和生产者全部都唤醒了
//Wakes up all threads that are waiting on this object's monitor(在消费者生产者问题中,说明唤醒了所有的生 //产者和消费者,因为锁是Store对象的).
this.notifyAll();
}
/**
* 从仓库中取走货物的方法
*/
public
synchronized void remove() {
while (cur_count <= 0) {
// 判断仓库中是否还有货物
System.out.println("仓库已空!");
try {
this.wait();// 如果为空则阻塞线程
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
--cur_count;// 取走货物,减少当前货物数量
// 打印当前货物数量
System.out.println(Thread.currentThread().toString()
+ " get ,current count:" + cur_count);
// 仓库不满,唤醒生产者线程
this.notifyAll();
}
}
/**
* @author Sun 生产者类
*/
class Producer extends Thread {
private Store s;
public Producer(Store s) {
super();
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (true) {
s.add();// 添加货物
try {
Thread.sleep(1000);// 休息1秒钟
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
/**
* @author Sun 消费者类
*/
class Consumer extends Thread {
private Store s;
public Consumer(Store s) {
super();
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (true) {
s.remove();// 取走货物
try {
Thread.sleep(1000);// 休息一秒钟
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}