线程不安全三大案例_卖票案例演示

package com.qiliang.demo13_线程同步安全;
// 线程同步安全问题 , 卖票案例演示
public class UnSafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"小A").start();
        new Thread(station,"小B").start();
        new Thread(station,"黄牛党").start();
    }
}


class BuyTicket implements Runnable{
    // 定义票数
    private int ticketNums = 10;
    // 线程停止的标志位
    boolean flag = true;
    @Override
    public void run() {
        // 买票
        while (flag){
            buy();
        }
    }

    private void buy() {
        // 判断是否有票
        if(ticketNums<=0){
            flag = false;
            return;
        }

        // 模拟延时,放大问题的发生性
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}
// 线程不安全, 有负数
/*
黄牛党拿到10
小B拿到9
小A拿到8
黄牛党拿到7
小B拿到6
小A拿到5
黄牛党拿到4
小B拿到3
小A拿到2
黄牛党拿到1
小B拿到0
小A拿到-1
 */
posted @ 2020-04-30 11:20  阿亮在努力  阅读(209)  评论(0)    收藏  举报