标签搜索

模拟线程不安全案例

admin
2025-04-03 / 0 评论 / 0 阅读 / 正在检测是否收录...

多个线程同时操作一个资源情况下,线程不安全,数据紊乱

//火车票抢票,模拟多个线程操作同一个对象
public class TicketThread implements  Runnable{
    private  int ticketNum = 10;
    @Override
    public void run() {
    while (true){
        if (ticketNum<=0){
            break;
        }
        System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNum--+"张票");
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    }
    public static void main(String[] args) {
        TicketThread ticketObj  = new TicketThread();
        new Thread(ticketObj,"小明").start();
        new Thread(ticketObj,"黄牛党").start();
        new Thread(ticketObj,"谱乾兄").start();
    }
}
0

评论 (0)

取消