并发问题:多线程抢火车票

当多个线程同时对一个资源进行访问的时候,就会出现以下问题:

package com.bes.mybatis_plus.Test1;

public class TestThread4 implements Runnable{
    //总火车票数
    private int ticketNums = 10;
    @Override
    public void run() {
        while(true){
            if(ticketNums <= 0){
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "拿到了第"+ ticketNums-- + "张票");
        }
    }

    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        //三个线程同时抢票
        new Thread(testThread4, "潘狗子").start();
        new Thread(testThread4, "阿米立卡").start();
        new Thread(testThread4, "黄牛").start();

    }
}

执行结果:

"黄牛拿到了第9张票
阿米立卡拿到了第10张票
潘狗子拿到了第9张票
阿米立卡拿到了第7张票
黄牛拿到了第8张票
潘狗子拿到了第6张票
阿米立卡拿到了第4张票
黄牛拿到了第3张票
潘狗子拿到了第5张票
潘狗子拿到了第2张票
黄牛拿到了第1张票
阿米立卡拿到了第2张票

Process finished with exit code 0

可以看到,第9张票,第2张票,同时被多个人拿到
这与现实情况矛盾,所以在多线程同时访问同一个资源时,会出现问题,所以需要对应的解决办法:加上锁解决并发问题

package com.bes.mybatis_plus.Test1;

public class TestThread4 implements Runnable {
    //总火车票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {


            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (this) {
                if (ticketNums <= 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
            }
        }
    }

    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();

        new Thread(testThread4, "潘狗子").start();
        new Thread(testThread4, "阿米立卡").start();
        new Thread(testThread4, "黄牛").start();

    }
}

执行结果:

潘狗子拿到了第10张票
黄牛拿到了第9张票
阿米立卡拿到了第8张票
阿米立卡拿到了第7张票
黄牛拿到了第6张票
潘狗子拿到了第5张票
潘狗子拿到了第4张票
黄牛拿到了第3张票
阿米立卡拿到了第2张票
潘狗子拿到了第1张票

Process finished with exit code 0

这只是很简单的一个加锁的应用,此文章只是介绍多线程出现的问题,想知道更多解决方法,后会有期

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值