针对java实验的思考(四)

题目:

模拟3个人排队买票,每人买1张票
售票员只有1张五元的钱,电影票五元钱一张
张某拿1张二十元的人民币排在孙某前面买票,孙某拿1张十元的人民币排在赵的前面买票,赵某拿1张五元的人民币排在最后

注意事项:

                构造函数前面不能加void!

           线程同步中 notifyAll();不需要注明对象。写在synchronized方法的最后就可以。


源代码:

import javax.xml.stream.events.StartDocument;

class test implements Runnable {
    Thread a=new Thread(this);
    Thread b=new Thread(this);
    Thread c=new Thread(this);
    int s1=5,s2=10,s3=20;
    int s[]={0,0,1};
    public synchronized void seller(int sx){
        if(sx==5){
            System.out.println("张三拿出"+sx+"块钱");
            s[2]++;
            System.out.println("张三买了票");
        }
        else if(sx==10){
                System.out.println("王大明拿出"+sx+"块钱");
                while(s[2]==0) {
                    System.out.println("王大明要等候");
                    try {
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
                s[1]++;
                s[2]--;
                System.out.println("王大明买了票");
        }
        else if(sx==20){
            System.out.println("赵乐乐拿出"+sx+"块钱");
            while(s[1]<1||s[2]<1){
                System.out.println("赵乐乐要等候");
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            s[0]++;
            s[1]--;
            s[2]--;
            System.out.println("赵乐乐买了票");
        }
        notifyAll();
    }
    test(){
        a.setName("张三");
        b.setName("王大明");
        c.setName("赵乐乐");
    }
    
    public void run() {
        if(Thread.currentThread()==a)
        {
            seller(s1);
        }
        if(Thread.currentThread()==b)
        {
            seller(s2);
        }
        if(Thread.currentThread()==c)
        {
            seller(s3);
        }
    }
}
public class test_thread{

    public static void main(String []args){
        test t1=new test();
        t1.a.start();
        t1.b.start();
        t1.c.start();
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值