海阔天空

当前时间为:
欢迎大家来到海阔天空https://www.9713job.com,广告合作以及淘宝商家推广请微信联系15357240395

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

未分类
2020-08-30 12:54:48
1822677238@qq.com

手机扫码查看

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--;
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注