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

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();
    }
}
相关推荐
超绝振刀怪6 分钟前
【C++多态】
开发语言·c++
workflower17 分钟前
AI制造-推荐初始步骤
java·开发语言·人工智能·软件工程·制造·需求分析·软件需求
zc.ovo20 分钟前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣26 分钟前
力扣热门100题之环形链表
算法·leetcode·链表
魔都吴所谓38 分钟前
【Python】从零构建:IP地理位置查询实战指南
开发语言·python·tcp/ip
py有趣38 分钟前
力扣热门100题之回文链表
算法·leetcode·链表
环黄金线HHJX.1 小时前
【吧里BaLi社区】
开发语言·人工智能·qt·编辑器
oioihoii1 小时前
Cursor根本无法调试C++
开发语言·c++