共享栈(多线程)

★带互斥的共享栈
多线程互斥共享“栈”资源

public class myStack {
//共享栈:先进后出
    int idx=0;
    char[] c=new char[9];
    void put(char ch){
        //同步块:对象锁是指定的
        synchronized (this) {
            c[idx++] = ch;
            System.out.println("push:"+ch);
            this.notify();
        }
    }
    //同步方法:对象锁是该方法的拥有者--静态方法是类,非静态是this对象
    public synchronized char pop(){
        if(idx<1){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        char ch=c[--idx];
        System.out.println("---pop:"+ch);
        return ch;
    }
}
public class pushThread extends Thread {

    myStack ms=null;
    public pushThread(myStack ms){
        this.ms=ms;
    }
    @Override
    public void run() {
        for(int i=97;i<103;i++){
            ms.put((char)i);
        }
    }
}
public class popThread extends Thread {
    myStack ms=null;
    public popThread(myStack ms){
        this.ms=ms;
    }
    @Override
    public void run() {
        for(int i=1;i<10;i++){
            ms.pop();
        }
    }
}
public class client {
    public static void main(String[] args) {
        myStack ms=new myStack();
        pushThread t1=new pushThread(ms);
        popThread t2=new popThread(ms);

        t1.start();
        t2.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值