题目:买火车票

窗口抢票简单实现

package com.gao.Project.Pro7;

public class BuyTicketThread extends Thread{
    //有参构造器
    public BuyTicketThread(String name){
        super(name);//调用父类构造器传名字
    }
    //一共10张票
    static int ticketNum = 10;  //多个对象共享10张票
    //每个窗口都是一个线程对象:每个对象执行的代码放入run方法中
    @Override
    public void run() {
        //每个窗口后面都有100个人在抢票
       for (int i = 1; i<=100; i++) {
           if(ticketNum > 0){//对票数进行判断
               System.out.println("我在"+this.getName()+"买到了北京到哈尔滨的第"+ ticketNum-- +"张车票");
           }
       }
    }
}

package com.gao.Project.Pro7;

public class Test {
    public static void main(String[] args) {
        //多个窗口抢票:三个窗口--->三个线程对象
        BuyTicketThread t1 = new BuyTicketThread("窗口1");
        t1.start();
        BuyTicketThread t2 = new BuyTicketThread("窗口2");
        t2.start();
        BuyTicketThread t3 = new BuyTicketThread("窗口3");
        t3.start();
    }
}

多次运行会出现错误错误:例如同一张票重复被购买,出现0票负数票等问题

窗口抢票加强版

package com.gao.Project.Pro8;

public class BuyTicketThread implements Runnable {//实现Runnable接口
    int ticketNum = 10;
    @Override
    public void run() {
        for (int i = 1; i <100 ; i++) {
            if (ticketNum>0){
                System.out.println("我在窗口"+Thread.currentThread().getName()+ "买到了北京到哈尔滨的第"+  ticketNum--  +"张车票");
            }

        }
    }
}

package com.gao.Project.Pro8;

import java.util.concurrent.TransferQueue;

public class Test {
    public static void main(String[] args) {
        //定义一个线程对象
        BuyTicketThread bt = new BuyTicketThread();
        //窗口1买票
        Thread bt1 = new Thread(bt,"窗口1");
        bt1.start();
        //窗口2买票
        Thread bt2 = new Thread(bt,"窗口2");
        bt2.start();
        //窗口3买票
        Thread bt3 = new Thread(bt,"窗口3");
        bt3.start();
    }
}

posted @   进步+吃饭  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示