@chenxuxiong
2016-05-23T04:51:16.000000Z
字数 1642
阅读 417
JAVA基础
设计模式
import java.util.Stack;
public class ProduceAndConsumer {
public static void main(String[] args) {
FactoryStack fs=new FactoryStack();
Producer p1=new Producer(fs,"PA");
Producer p2=new Producer(fs,"PB");
Consumer c1=new Consumer(fs,"CA");
Consumer c2=new Consumer(fs,"CB");
new Thread(p1).start();
new Thread(p2).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
class Car{
int id;
Car(int id ){
this.id=id;
}
public String toString(){
return "Car :" +id;
}
}
class FactoryStack{
private Stack<Car> cars=new Stack<Car>();
public synchronized void push(Car car){
while(cars.size()>=6){
try {
System.out.println("仓库已满,等待消费");
this.wait();
} catch (InterruptedException e) {
}
}
this.notify(); //唤醒等待的线程进行消费
cars.add(car);
}
public synchronized Car pop(){
while(cars.size()==0){
System.out.println("存货不足,等待生产");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
return cars.pop();
}
/*
* int index=0;
* Car[] cars=new Car[6];
* public void push(Car car){
* cars[index]=car;
* }
* public synchronized Car pop(){
* index--;
return cars[index];
}
*
* */
}
class Producer implements Runnable{
private FactoryStack fs=null;
private String name;
Producer(FactoryStack fs,String name){
this.fs=fs;
this.name=name;
}
@Override
public void run() {
for(int i=1;i<20;i++){
Car car=new Car(i);
fs.push(car);
System.out.println(name+" create car "+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private FactoryStack fs=null;
private String name;
Consumer(FactoryStack fs,String name){
this.fs=fs;
this.name=name;
}
@Override
public void run() {
for(int i=1;i<20;i++){
Car car=fs.pop();
System.out.println(name+" get car "+car.id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}