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

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();
    }
}
相关推荐
木子墨5163 分钟前
LeetCode 热题 100 精讲 | 并查集篇:最长连续序列 · 岛屿数量 · 省份数量 · 冗余连接 · 等式方程的可满足性
数据结构·c++·算法·leetcode
Ava的硅谷新视界41 分钟前
用了一天 Claude Opus 4.7,聊几点真实感受
开发语言·后端·编程
rabbit_pro41 分钟前
Python调用onnx模型
开发语言·python
王老师青少年编程1 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:均分纸牌
c++·算法·编程·贪心·csp·信奥赛·均分纸牌
EQUINOX11 小时前
2026年码蹄杯 本科院校赛道&青少年挑战赛道提高组初赛(省赛)第一场,个人题解
算法
萝卜小白1 小时前
算法实习Day04-MinerU2.5-pro
人工智能·算法·机器学习
Liangwei Lin1 小时前
洛谷 P3133 [USACO16JAN] Radio Contact G
数据结构·算法
一 乐1 小时前
医院挂号|基于springboot + vue医院挂号管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·医院挂号管理系统
weixin_513449962 小时前
PCA、SVD 、 ICP 、kd-tree算法的简单整理总结
c++·人工智能·学习·算法·机器人
浪客川2 小时前
【百例RUST - 010】字符串
开发语言·后端·rust