笔记20200524:多线程【三大不安全案例】

案例一
package com.chengguo.线程;

/**
 * 同步锁之买票不安全的情况演示
 */
public class Demo_20200523001_SynchronizedUnsafe {
    public static void main(String[] args) {
        //创建对象调用方法执行
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "农民工").start();
        new Thread(buyTicket, "黄牛党").start();
        new Thread(buyTicket, "我自己").start();
    }


}

class BuyTicket implements Runnable {
    //买票首先得有票
    private int ticketNum = 10;
    //定义一个标志位用来外部停止线程
    boolean flag = true;

    @Override
    public void run() {
        //调用方法买票
        while (true) {
            buy();
        }
    }


    //买票的方法
    public void buy() {
        //判断是否有票
        if (ticketNum <= 0) {
            flag = false;
            return;
        } else {
            try {
                //模拟延时
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //买票
            System.out.println(Thread.currentThread().getName() + "买到第" + ticketNum-- + "张票");
        }


    }
}

  

posted @ 2020-06-18 17:29  忧桑の民工  阅读(142)  评论(0编辑  收藏  举报