创建线程实现火车站多窗口买票问题

1.首先要知道创建线程的方式

(1)通过继承Thread类的方式

(2)通过实现runnable的方式

2.多个线程(多个窗口)卖票这里要考虑线程安全问题,不然会出现错票和重票的问题。这里有上面两种方式实现

(1)通过继承thread类实现

复制代码
public class CreateThread extends Thread{

    static int ticket = 100;

    boolean isFlag = true;
    public void run(){
        while(isFlag){
            show();
        }
    }

    public synchronized void show(){
        synchronized (CreateThread.class) {
            if(ticket>0){
                System.out.println(currentThread().getName()+ticket);
                ticket--;
            }else{
                isFlag=false;
            }
        }
    }

    public static void main(String[] args) {
        CreateThread t1 = new CreateThread();
        t1.start();
        CreateThread t2 = new CreateThread();
        t2.start();
        CreateThread t3 = new CreateThread();
        t3.start();

    }

}

这里要非常注意如果使用同步代码块,这个同步监视器的对象,如果是继承方式实现的,那么就要使用CreateThread.class.

(2)通过实现Runnable的方式实现,使用同步代码块,这个同步监视器可以直接使用this.因为实现runnable接口的实现类的对象只有一个,可以实现同步机制。

复制代码
public class CreateThreadII implements Runnable{

    static int ticket =100;
    @Override
    public void run() {
        while(true){
            synchronized (this){
                if(ticket>0){                    System.out.println(Thread.currentThread().getName()+"======>"+ticket);
                    ticket--;

                }
            }

        }
    }
    public static void main(String[] args) {
        CreateThreadII createThreadII = new CreateThreadII();
        Thread t1 = new Thread(createThreadII);
        t1.start();
        Thread t2 = new Thread(createThreadII);
        t2.start();
        Thread t3 = new Thread(createThreadII);
        t3.start();
    }
}
相关推荐
逑之1 小时前
C语言笔记10:sizeof和strlen,指针与数组
c语言·笔记·算法
求梦8201 小时前
【力扣hot100题】旋转图像(15)
算法·leetcode·职场和发展
海边的Kurisu2 小时前
苍穹外卖日记 | Day1 苍穹外卖概述、开发环境搭建、接口文档
java
C雨后彩虹5 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..5 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X5 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
SmartRadio7 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion7 小时前
QT5.7.0编译移植
开发语言·qt
少林码僧7 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
钱彬 (Qian Bin)7 小时前
项目实践15—全球证件智能识别系统(切换为Qwen3-VL-8B-Instruct图文多模态大模型)
人工智能·算法·机器学习·多模态·全球证件识别