2021-10-20 售票问题(多线程)


public class TestTicket {

    public static void main(String[] args) {

        Runnable st = new SellTicket(new Tick());
        new Thread(st, "A").start();
        new Thread(st, "B").start();
        new Thread(st, "C").start();
        new Thread(st, "D").start();
    }

    public static class SellTicket implements Runnable {

        public Tick tick;
        
        Object mutex = new Object();

        public SellTicket(Tick tick) {
            this.tick = tick;
        }

        public void run() {
                
                while (tick.getCount() > 0) {
                    synchronized(mutex) { //需要有一个锁变量
                        if(tick.getCount() <=0) break; //synchronized之前没锁住其他线程(有可能进入到while等待,当进入后需要重新判断count值是大于0,不然就会变成0或负数)
                        int temp = tick.getCount(); 
                        System.out.println(Thread.currentThread().getName()
                                + "-----sale" + temp--);
                        
                         tick.setCount(temp); 
                    }
                }
            
        }
    }

    public static class Tick {
        private int count = 10;

        private Tick() {
        }

        private static final class lazyhodler {
            public static final Tick INSTANCE = new Tick();
        }

        public static final Tick getInstance() {
            return lazyhodler.INSTANCE;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

    }
}

结果:

A-----sale10
A-----sale9
A-----sale8
A-----sale7
A-----sale6
A-----sale5
A-----sale4
A-----sale3
A-----sale2
A-----sale1

java实现多线程的两种方式及售票实例icon-default.png?t=L9C2https://www.cnblogs.com/jiansen/p/7347426.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值