多线程_模拟抢票

初始并发问题

来源:https://www.bilibili.com/video/BV1V4411p7EF?p=12

多个线程操作同一个资源,就会造成数据紊乱,线程不安全

package com.hao.Demo01;

//多个线程操作同一个对象
//买火车票
public class TestThread03 implements Runnable {

    //票
    private int TicketNums = 10;

    @Override
    public void run() {

        while (true){
            if(TicketNums<=0){
                break;
            }
            //模拟延时,抢票
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"---->拿到了第"+TicketNums--+"票");
        }
    }

    public static void main(String[] args) {
        TestThread03 ticket = new TestThread03();

        new Thread(ticket,"小名").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛党").start();
    }
}
posted @ 2021-02-10 17:51  多愚  阅读(88)  评论(0编辑  收藏  举报