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

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();
    }
}
相关推荐
数模竞赛Paid answer21 分钟前
2025年MathorCup数学建模A题汽车风阻预测解题文档与程序
算法·数学建模·mathorcup
xin_nai24 分钟前
LeetCode热题100(Java)(6)矩阵
java·leetcode·矩阵
geovindu25 分钟前
go: Visitor Pattern
开发语言·设计模式·golang·访问者模式
宣宣猪的小花园.26 分钟前
C语言重难点全解析:内存管理到位运算
c语言·开发语言·单片机
方安乐4 小时前
python之向量、向量和、向量点积
开发语言·python·numpy
代码AI弗森6 小时前
一文理清楚“算力申请 / 成本测算 / 并发评估”
java·服务器·数据库
Old Uncle Tom6 小时前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
会编程的土豆6 小时前
洛谷题单入门1 顺序结构
数据结构·算法·golang
小小小米粒6 小时前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
生信碱移6 小时前
PACells:这个方法可以鉴定疾病/预后相关的重要细胞亚群,作者提供的代码流程可以学习起来了,甚至兼容转录组与 ATAC 两种数据类型!
人工智能·学习·算法·机器学习·数据挖掘·数据分析·r语言