JDBC线程_出售火车票

该博客介绍了如何使用Java的多线程技术实现一个模拟三个窗口同时售卖火车票的系统。通过实现Runnable接口,创建并启动多个线程来展示并发售票的过程。
摘要由CSDN通过智能技术生成

需求:
三个窗口同时卖票,用实现Runnable方式

public class T_Card implements Runnable{//也可继承Thread
    static int currCard=50;
    static Object obj=new Object();
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);//使当前执行的线程休眠(暂停执行)用于指定的毫秒数
            synchronized (obj){
                if (currCard>0){
                    System.out.println("线程编号:"+Thread.currentThread().getName()+"   "+"卖出的票是:"+currCard);
                    currCard--;
                }else {
                    System.out.println("该车次的票已售完......");
                    System.exit(0);
                }
            }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        T_Card tc1=new T_Card();
        Thread t1=new Thread(tc1);
        t1.start();//开启线程1

        T_Card tc2=new T_Card();
        Thread t2=new Thread(tc2);
        t2.start();//开启线程2

        T_Card tc3=new T_Card();
        Thread t3=new Thread(tc3);
        t3.start();//开启线程3
    }

执行结果:

线程编号:Thread-2   卖出的票是:20
线程编号:Thread-1   卖出的票是:19
线程编号:Thread-0   卖出的票是:18
线程编号:Thread-1   卖出的票是:17
线程编号:Thread-0   卖出的票是:16
线程编号:Thread-2   卖出的票是:15
线程编号:Thread-1   卖出的票是:14
线程编号:Thread-2   卖出的票是:13
线程编号:Thread-0   卖出的票是:12
线程编号:Thread-1   卖出的票是:11
线程编号:Thread-0   卖出的票是:10
线程编号:Thread-2   卖出的票是:9
线程编号:Thread-1   卖出的票是:8
线程编号:Thread-2   卖出的票是:7
线程编号:Thread-0   卖出的票是:6
线程编号:Thread-1   卖出的票是:5
线程编号:Thread-0   卖出的票是:4
线程编号:Thread-2   卖出的票是:3
线程编号:Thread-1   卖出的票是:2
线程编号:Thread-2   卖出的票是:1
该车次的票已售完......

Process finished with exit code 0
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值