您的位置:首页 > 其它

生产者模式

2015-11-14 21:48 239 查看
public class Main {
public static void main(String[] args){
Stack stack=new Stack("栈程1");
Producer pro=new Producer(stack,"生产者");
Consumer con=new Consumer(stack,"消费者");
}
}

//生产者
class Producer extends Thread{
private Stack stack;

public Producer(Stack stack,String name) {
super(name);
this.stack = stack;
start();
}

@Override
public void run() {
for(int i=0;i<100;i++){
String good= "good" + (this.stack.getIndex() + 1);
this.stack.push(good);
System.out.println(getName() + ": 压入 " + good + " " + " 成功");
Thread.yield();
}
}
}

//消费者
class Consumer extends Thread {
private Stack stack;

public Consumer(Stack stack,String name) {
super(name);
this.stack = stack;
start();
}

@Override
public void run() {
for(int i=0;i<100;i++){
//good="获得"+this.stack.pop(i);
String good=this.stack.pop();
//System.out.println(good);
System.out.println(getName() + ": 取出 " + good + " " + " 成功");
Thread.yield();
}
}
}

class Stack {
private String name;
private boolean flag=false; //红绿灯
private String[] buffers=new String[100];  //争夺的资源
private int index=-1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String[] getBuffers() {
return buffers;
}
public Stack(String name) {
super();
this.name = name;
}
public Stack() {
super();
}
public void setBuffers(String[] buffers) {
this.buffers = buffers;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}

//============================================
//弹栈
public synchronized String pop() {
try {
if(!flag){
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

String str=buffers[index];
buffers[index]=null;
Thread.yield();
index--;
flag=false;
this.notifyAll();
return str;
}
//压栈
public synchronized void push(String good) {
try {
if(flag){
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
index++;
Thread.yield();
buffers[index]=good;
flag=true;
this.notifyAll();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: