java线程同步实现窗口售票机制

public class TextDemo {
    public static void main(String[] args) {
        TheRules theRules01=new TheRules(10);
        ticketThread thd1=new ticketThread("窗口1:",theRules01,5);
        ticketThread thd2=new ticketThread("窗口2:",theRules01,5);
        ticketThread thd3=new ticketThread("窗口3:",theRules01,5);
        thd1.start();
        thd2.start();
        thd3.start();

    }
}
//票机制
class TheRules{
    //总票数
    Integer ticket;

    public TheRules(Integer ticket) {
        this.ticket = ticket;
    }
                                        //售出的票
    public  synchronized void rulesSyten(int myCount){
        if(ticket==0){
            System.out.println("票没了");
            return;
        }
        if(myCount>ticket){
            System.out.println("票量不足");
        }else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket=ticket-myCount;
            System.out.println(Thread.currentThread().getName()+"售出"+myCount+"张票,剩余"+ticket);
        }


    }
}

class ticketThread extends Thread{
    private TheRules theRules;
    private int myCount;

    public ticketThread(String name, TheRules theRules,int myCount) {
        super(name);
        this.theRules = theRules;
        this.myCount=myCount;
    }

    @Override
    public void run() {
        theRules.rulesSyten(myCount);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值