Java零基础学java之多线程--15线程不安全案例01

package com.li.thread_synchronized;

//不安全买票
public class UnsafeBuyTicket {

    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 ticketNums = 10;
    boolean flag = true;//标志位停止

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    public void buy() throws InterruptedException {
        //没票了
        if (ticketNums<=0) {
            flag = false;
        }
        //模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "-->拿到了" + ticketNums--);
    }
}

猜你喜欢

转载自blog.csdn.net/l1341886243/article/details/118383408