2020java教程:匿名内部类完成生产者和消费者

匿名内部类完成生产者和消费者

public class demos{
    public static void main(String[] args) {
        MyStack ms=new MyStack();
        Thread t1=new Thread(){
            public void run() {
                for(char c='A';c<='Z';c++){
                    ms.push(c+"");
                }
            }
        };
        Thread t2=new Thread(){
            public void run() {
                for(int i=0;i<26;i++){
                    ms.poll();
                }
            }
        };
        t1.start();
        t2.start();
    }
}
class MyStack{
    private String[] values={"","","","",""};
    private int size=0;
    public synchronized void push(String s){
        this.notifyAll();
        while(values.length==size){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(s+"入栈");
        values[size]=s;
        size++;
    }
    public synchronized void poll(){
        this.notifyAll();
        while(size==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(values[size-1]+"出栈");
        values[size-1]="";
        size--;
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *