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

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();
    }
}
相关推荐
sycmancia13 分钟前
Qt——编辑交互功能的实现
开发语言·qt
RyFit29 分钟前
SpringAI 常见问题及解决方案大全
java·ai
石山代码42 分钟前
C++ 内存分区 堆区
java·开发语言·c++
心中有国也有家1 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事1 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
无风听海1 小时前
C# 隐式转换深度解析
java·开发语言·c#
碧海银沙音频科技研究院1 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
一只大袋鼠2 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
csdn_aspnet2 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展