多线程 模拟火车票售卖场景

本文通过一个火车票售卖的场景,展示了如何使用Java的多线程技术来实现三个售票窗口并发操作,确保了在高并发情况下火车票数量的准确性。通过synchronized关键字保证了线程间的同步,避免了超发或错发的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、模拟火车票售卖场景,三个窗口售卖A-B地的火车票,火车票共100张。

要求:
编号1-100 打印示例:窗口1售卖火车票66
窗口:写3个线程,


import java.util.Random;

/**
 * @auther: 巨未
 * @DATE: 2019/4/12 0012 23:18
 * @Description:
 */
class Tickets {

    private static int num = 0;

    public static synchronized int sale() {
        int i = ++num;
        return i> 100?-1:i;  //如果i>100返回-1.小于100返回i
    }
}
public class SaleTickets {
    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                Random random = new Random();
                int i = 0;
                while ((i = Tickets.sale()) != -1) {
                    System.out.println(Thread.currentThread().getName() + "售卖票:" + i);
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }, "窗口1");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Random random = new Random();
                int i = 0;
                while ((i = Tickets.sale()) != -1) {
                    System.out.println(Thread.currentThread().getName() + "售卖票:" + i);
                    try {
                        Thread.sleep(random.nextInt(2000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }, "窗口2");
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                Random random = new Random();
                int i = 0;
                while ((i = Tickets.sale()) != -1) {
                    System.out.println(Thread.currentThread().getName() + "售卖票:" + i);
                    try {
                        Thread.sleep(random.nextInt(2000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }, "窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
        }
}

运行示例:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值