生产者与消费者

来源:互联网 发布:sql code 803 编辑:程序博客网 时间:2024/05/23 13:36
//生产者与消费者public class SyschTest {    public static void main(String[] args) {        Stack stack  = new Stack("stack");        Producer p = new Producer(stack, "p");        Consumer c = new Consumer(stack, "c");    }}class Stack {    private static String name;    private static String buffer[] = new String[100];    private static int point = -1;    public Stack(String name) {        this.name  =  name;    }    public String getName() {        return name;    }    public int getPoint() {        return point;    }    public int size() {        return point+1;    }    //入栈    public synchronized void push(String goods) {        point ++ ;        Thread.yield();        buffer[point] = goods ;    }    //出栈    public synchronized String pop() {        if(point == -1) {            return null;        }        String goods = buffer[point];        buffer[point] = null;        Thread.yield();        point --;        return goods;    }}//生产者class Producer extends Thread{    private String name ;    private Stack theStack;    public Producer(Stack s,String name) {        this.name = name;        this.theStack = s;        start();    }    public void run(){        String goods = null ;        for(int i =0;i<20;i++){            goods =  "goods"+ (theStack.getPoint()+1);            theStack.push(goods);            System.out.println(name + " push "+ goods +" into "+theStack.getName());            yield();        }    }} //消费者class Consumer extends Thread {    private String name ;    private Stack theStack;    public Consumer(Stack s,String name){        this.theStack = s;        this.name = name;        start();    }    public void run(){        String goods = null;        for(int i=0;i<20;i++) {            goods = theStack.pop();            System.out.println(name +" pop " + goods + " from " +theStack.getName());            yield();        }    }}
0 0
原创粉丝点击