百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术流 > 正文

看了这个有趣的例子,相信你就秒懂多线程同步了

citgpt 2024-08-01 13:30 8 浏览 0 评论


电影票的案例

单线程的例子

我们设定有一个电影院,该电影院开张不久,在入口的旁边只设立了一个售票点A,顾客看电影,需要在售票点排队依次买票,买完票后在入口处检票进入电影院观影。

看了这个有趣的例子,相信你就秒懂多线程同步了

上面的描述用代码来实现,可以是这样的:1、首先建立一个电影票的类:主要的属性有票的ID,哪个放映厅,哪一排哪一列,放映的电影名称,放映时间及票价。

/**
 * 通过卖票程序读懂多线程--电影票的类
 *
 * @author zhuhuix
 * @date 2020-05-12
 */
public class Ticket {

    //id
    private int ticketId;
    //放映厅
    private String room;
    //行
    private Integer row;
    //列
    private Integer col;
    //电影名
    private String filmName;
    //价格
    private BigDecimal price;
    //放映时间
    private LocalDateTime datetime;

    private Ticket(){

    }

    public Ticket(int ticketId,String room, Integer row, Integer col, String filmName, BigDecimal price, LocalDateTime datetime) {
        this.ticketId = ticketId;
        this.room = room;
        this.row = row;
        this.col = col;
        this.filmName = filmName;
        this.price = price;
        this.datetime = datetime;
    }

    public int getTicketId() {
        return ticketId;
    }

    public void setTicketId(int ticketId) {
        this.ticketId = ticketId;
    }

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public Integer getRow() {
        return row;
    }

    public void setRow(Integer row) {
        this.row = row;
    }

    public Integer getCol() {
        return col;
    }

    public void setCol(Integer col) {
        this.col = col;
    }

    public String getFilmName() {
        return filmName;
    }

    public void setFilmName(String filmName) {
        this.filmName = filmName;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public LocalDateTime getDatetime() {
        return datetime;
    }

    public void setDatetime(LocalDateTime datetime) {
        this.datetime = datetime;
    }

    @Override
    public String toString() {
        return "Ticket{" +
                "ticketId=" + ticketId +
                ", room='" + room + '\'' +
                ", row=" + row +
                ", col=" + col +
                ", filmName='" + filmName + '\'' +
                ", price=" + price +
                ", datetime=" + datetime +
                '}';
    }
}

2、其次建立一个顾客的类:主要的属性有票的ID,购买的电影票;成员方法有买票。

/**
 * 通过卖票程序读懂多线程--顾客类
 *
 * @author zhuhuix
 * @date 2020-05-12
 */
public class Customer {
    //顾客id
    private int customerId;
    //购买的电影票
    private Ticket ticket;

    public Customer(int customerId) {
        this.customerId = customerId;
    }

    //顾客买票
    public void buyTicket(Ticket ticket) {
        this.ticket = ticket;
    }

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public Ticket getTicket() {
        return ticket;
    }

    public void setTicket(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "customerId=" + customerId +
                ", ticket=" + ticket.toString() +
                '}';
    }
}

3、最后写一个主程序,生成电影票的列表,设定上门观影的顾客人数,依次买票,输出电影票购买的状态。

/**
 * 通过卖票程序读懂多线程--单线程程序
 *
 * @author zhuhuix
 * @date 2020-05-12
 */
public class TicketSingle {

    private static final String ROOM = "中央放映厅";
    private static final int ROW = 10;
    private static final int COL = 20;
    private static final String FILM_NAME = "战狼3";
    private static final BigDecimal PRICE = BigDecimal.valueOf(30);

    private static List<Ticket> tickets = new ArrayList<>();

    private static final int CUSTOMER_COUNT = 250;
    private static List<Customer> customers = new ArrayList<>(CUSTOMER_COUNT);

    public static void main(String[] args) {
        //中央放映厅总共有250个座位,2020-05-12 18:00 放映战狼3,售票价格为30元
        int ticketId=1;
        for (int row = 1; row <= ROW; row++) {
            for (int col = 1; col <= COL; col++) {
                Ticket ticket = new Ticket(ticketId++, ROOM, row, col,
                        FILM_NAME, PRICE,
                        LocalDateTime.of(2020, 5, 10, 18, 00));
                tickets.add(ticket);
            }
        }
        Iterator<Ticket> iterator = tickets.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toString());

        }

        //顾客到售票点进行随机买票
        Collections.shuffle(tickets);
        int index = 1;
        while (tickets.size() > 0 && index <= CUSTOMER_COUNT) {
            Ticket ticket = tickets.get(tickets.size() - 1);

            Customer customer = new Customer(index);
            customer.buyTicket(ticket);
            customers.add(customer);

            tickets.remove(ticket);

            System.out.println(tickets.size() + "," + index);
            System.out.println(index + "号顾客买到了"
                    + "第" + customer.getTicket().getRow() + "行,第" + customer.getTicket().getCol() + "列的票");
            index++;
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("电影票出售情况如下:");
        //剩余票的状态
        System.out.println("剩余票数:" + tickets.size());
        Iterator<Ticket> ticketIterator = tickets.iterator();
        while (ticketIterator.hasNext()) {
            System.out.println(ticketIterator.next().toString());
        }
        //顾客购买情况
        System.out.println("买到票的人数:" + customers.size());
        Iterator<Customer> customerIterator = customers.iterator();
        while (customerIterator.hasNext()) {
            System.out.println(customerIterator.next().toString());
        }
        System.out.println("未买到票的人数:" +(CUSTOMER_COUNT- customers.size()));

    }
}

主程序的输出情况是这样的:

从单线程转向多线程

一切井然有序,程序也运行得很好,那我们继续往 下看,由于观影顾客人数的增加,电影院对放映厅做了改造:1、增加座位;2、增设两个卖票窗口。也就说原来只有一个窗口排队单通道执行的程序变了,要允许原来的售票点与新增的售票点,同时进行卖票了。

有问题的多线程的例子

我们先简单的在单线程的程序上做个多线程的改造:建立一个多线程的类,重写run方法,将顾客买票的过程移至run方法中,在主程中设立”售票点A“,”售票点B“,”售票点C“三个线程让其同时运行,对了,别忘了把ArrayList这个数据结构也改成Vector。改造后的程序是这样的:

/**
 * 通过卖票程序读懂多线程--多线程
 *
 * @author zhuhuix
 * @date 2020-05-12
 */
public class TicketThread extends Thread {
    private static final String ROOM = "中央放映厅";
    private static final int ROW = 20;
    private static final int COL = 30;
    private static final String FILM_NAME = "战狼3";
    private static final BigDecimal PRICE = BigDecimal.valueOf(30);

    private static List<Ticket> tickets = new Vector<>();

    private static final int CUSTOMER_COUNT = 800;
    private static int customerId = 1;
    private static List<Customer> customers = new Vector<>(CUSTOMER_COUNT);

    TicketThread(String name) {
        super(name);

    }

    @Override
    public void run() {

        while (tickets.size() > 0 && customerId <= CUSTOMER_COUNT) {
                Ticket ticket = tickets.get(tickets.size() - 1);
                ticket.setWindow(Thread.currentThread().getName());
                Customer customer = new Customer(customerId);
                customer.buyTicket(ticket);
                customers.add(customer);

                tickets.remove(ticket);

                System.out.println(tickets.size() + "," + customerId);
                System.out.println(Thread.currentThread().getName() + ":" + customerId + "号顾客买到了"
                        + "第" + customer.getTicket().getRow() + "行,第" + customer.getTicket().getCol() + "列的票");
                customerId++;
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    public static void main(String[] args) throws InterruptedException {
        //中央放映厅总共有250个座位,2020-05-12 18:00 放映战狼3,售票价格为30元
        int ticketId = 1;
        for (int row = 1; row <= ROW; row++) {
            for (int col = 1; col <= COL; col++) {
                Ticket ticket = new Ticket(ticketId++, ROOM, row, col,
                        FILM_NAME, PRICE,
                        LocalDateTime.of(2020, 5, 10, 18, 00));
                tickets.add(ticket);
            }
        }
        Iterator<Ticket> iterator = tickets.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toString());

        }

        //顾客到售票点进行随机买票
        Collections.shuffle(tickets);

        TicketThread ticketThreadA = new TicketThread("售票点A");
        TicketThread ticketThreadB = new TicketThread("售票点B");
        TicketThread ticketThreadC = new TicketThread("售票点C");

        ticketThreadA.start();
        ticketThreadB.start();
        ticketThreadC.start();

        ticketThreadA.join();
        ticketThreadB.join();
        ticketThreadC.join();

        System.out.println("电影票出售情况如下:");
        //剩余票的状态
        System.out.println("总共票数:" + ROW * COL + ",剩余票数:" + tickets.size());
        Iterator<Ticket> ticketIterator = tickets.iterator();
        while (ticketIterator.hasNext()) {
            System.out.println(ticketIterator.next().toString());
        }
        //顾客购买情况
        System.out.println("买到票的人数:" + customers.size());
        Iterator<Customer> customerIterator = customers.iterator();
        while (customerIterator.hasNext()) {
            System.out.println(customerIterator.next().toString());
        }
        System.out.println("未买到票的人数:" + (CUSTOMER_COUNT - customers.size()));

    }
}

运行一下:总共只有600张票,买到票的人有614人?那进了电影院顾客肯定得投诉。

线程同步问题

我们分析一下:电影票总共只有600张,三个窗口同时卖这600张票,电影票是个共享的池子,在多线程术语上称为”共享资源“或”临界资源“,每个线程访问这些资源时,要保证”同步“:售票点A要卖第10排第9列的座位时,当且仅当同一时刻只有售票点A才能访问这个座位对应的电影票,也就是所谓的不能一票多卖。

那多线程如何保证同步?通过加锁!! 加锁是用来控制多个线程访问共享资源的方式,一般来说,一个锁能够防止多个线程同时访问共享资源。

保证线程同步的例子

为了可以简单地说明加锁可以保证多线程同步,在下面的例子中仅实现对电影票共享池进行加锁。

/**
 * 通过卖票程序读懂多线程--多线程
 *
 * @author zhuhuix
 * @date 2020-05-12
 */
public class TicketThread extends Thread {
    private static final String ROOM = "中央放映厅";
    private static final int ROW = 20;
    private static final int COL = 30;
    private static final String FILM_NAME = "战狼3";
    private static final BigDecimal PRICE = BigDecimal.valueOf(30);

    private volatile static List<Ticket> tickets = new Vector<>();

    private static final int CUSTOMER_COUNT = 800;
    private static int customerId = 1;
    private volatile static List<Customer> customers = new Vector<>(CUSTOMER_COUNT);

    TicketThread(String name) {
        super(name);

    }

    @Override
    public void run() {

        while (tickets.size() > 0 && customerId <= CUSTOMER_COUNT) {
            synchronized (TicketThread.class) {
             //线程内两次判断,防止tickets 数组溢出
              if (tickets.size()>0) {
                Ticket ticket = tickets.get(tickets.size() - 1);
                ticket.setWindow(Thread.currentThread().getName());
                Customer customer = new Customer(customerId);
                customer.buyTicket(ticket);
                customers.add(customer);

                tickets.remove(ticket);

                System.out.println(tickets.size() + "," + customerId);
                System.out.println(Thread.currentThread().getName() + ":" + customerId + "号顾客买到了"
                        + "第" + customer.getTicket().getRow() + "行,第" + customer.getTicket().getCol() + "列的票");
                customerId++;
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              }
           } 
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //中央放映厅总共有250个座位,2020-05-12 18:00 放映战狼3,售票价格为30元
        int ticketId = 1;
        for (int row = 1; row <= ROW; row++) {
            for (int col = 1; col <= COL; col++) {
                Ticket ticket = new Ticket(ticketId++, ROOM, row, col,
                        FILM_NAME, PRICE,
                        LocalDateTime.of(2020, 5, 10, 18, 00));
                tickets.add(ticket);
            }
        }
        Iterator<Ticket> iterator = tickets.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toString());

        }

        //顾客到售票点进行随机买票
        Collections.shuffle(tickets);

        TicketThread ticketThreadA = new TicketThread("售票点A");
        TicketThread ticketThreadB = new TicketThread("售票点B");
        TicketThread ticketThreadC = new TicketThread("售票点C");

        ticketThreadA.start();
        ticketThreadB.start();
        ticketThreadC.start();

        ticketThreadA.join();
        ticketThreadB.join();
        ticketThreadC.join();

        System.out.println("电影票出售情况如下:");
        //剩余票的状态
        System.out.println("总共票数:" + ROW * COL + ",剩余票数:" + tickets.size());
        Iterator<Ticket> ticketIterator = tickets.iterator();
        while (ticketIterator.hasNext()) {
            System.out.println(ticketIterator.next().toString());
        }
        //顾客购买情况
        System.out.println("买到票的人数:" + customers.size());
        Iterator<Customer> customerIterator = customers.iterator();
        while (customerIterator.hasNext()) {
            System.out.println(customerIterator.next().toString());
        }
        System.out.println("未买到票的人数:" + (CUSTOMER_COUNT - customers.size()));

    }
}

运行情况如下:票不超卖了:

每个窗口也实现了同步并发卖票:

同步的代码主要的改变来自于:1、将卖票的过程用synchronized修饰,实现锁的互斥,具体可以参考java多线程:synchronized的深度理解

synchronized (TicketThread.class) {
                Ticket ticket = tickets.get(tickets.size() - 1);
                ticket.setWindow(Thread.currentThread().getName());
                Customer customer = new Customer(customerId);
                customer.buyTicket(ticket);
                customers.add(customer);

                tickets.remove(ticket);

                System.out.println(tickets.size() + "," + customerId);
                System.out.println(Thread.currentThread().getName() + ":" + customerId + "号顾客买到了"
                        + "第" + customer.getTicket().getRow() + "行,第" + customer.getTicket().getCol() + "列的票");
                customerId++;
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

2、将共享资源用volatile 修饰,实现线程访问的可视化,具体可以参考java多线程:volatile的深度理解

private volatile static List<Ticket> tickets = new Vector<>();
private volatile static List<Customer> customers = new Vector<>(CUSTOMER_COUNT);

写在最后

程序所有的表达,归根到底都是逻辑问题。而逻辑的核心是清晰高效地思考问题。对于多线程的理解,大家一定要起手来写一些例程,融汇贯通才能体会到真谛,才能真正应用到工作实践中去。

相关推荐

js中arguments详解

一、简介了解arguments这个对象之前先来认识一下javascript的一些功能:其实Javascript并没有重载函数的功能,但是Arguments对象能够模拟重载。Javascrip中每个函数...

firewall-cmd 常用命令

目录firewalldzone说明firewallzone内容说明firewall-cmd常用参数firewall-cmd常用命令常用命令 回到顶部firewalldzone...

epel-release 是什么

EPEL-release(ExtraPackagesforEnterpriseLinux)是一个软件仓库,它为企业级Linux发行版(如CentOS、RHEL等)提供额外的软件包。以下是关于E...

FullGC详解  什么是 JVM 的 GC
FullGC详解 什么是 JVM 的 GC

前言:背景:一、什么是JVM的GC?JVM(JavaVirtualMachine)。JVM是Java程序的虚拟机,是一种实现Java语言的解...

2024-10-26 08:50 citgpt

使用Spire.Doc组件利用模板导出Word文档
  • 使用Spire.Doc组件利用模板导出Word文档
  • 使用Spire.Doc组件利用模板导出Word文档
  • 使用Spire.Doc组件利用模板导出Word文档
  • 使用Spire.Doc组件利用模板导出Word文档
跨域(CrossOrigin)

1.介绍  1)跨域问题:跨域问题是在网络中,当一个网络的运行脚本(通常时JavaScript)试图访问另一个网络的资源时,如果这两个网络的端口、协议和域名不一致时就会出现跨域问题。    通俗讲...

微服务架构和分布式架构的区别

1、含义不同微服务架构:微服务架构风格是一种将一个单一应用程序开发为一组小型服务的方法,每个服务运行在自己的进程中,服务间通信采用轻量级通信机制(通常用HTTP资源API)。这些服务围绕业务能力构建并...

深入理解与应用CSS clip-path 属性
深入理解与应用CSS clip-path 属性

clip-pathclip-path是什么clip-path 是一个CSS属性,允许开发者创建一个剪切区域,从而决定元素的哪些部分可见,哪些部分会被隐...

2024-10-25 11:51 citgpt

HCNP Routing&Switching之OSPF LSA类型(二)
  • HCNP Routing&Switching之OSPF LSA类型(二)
  • HCNP Routing&Switching之OSPF LSA类型(二)
  • HCNP Routing&Switching之OSPF LSA类型(二)
  • HCNP Routing&Switching之OSPF LSA类型(二)
Redis和Memcached的区别详解
  • Redis和Memcached的区别详解
  • Redis和Memcached的区别详解
  • Redis和Memcached的区别详解
  • Redis和Memcached的区别详解
Request.ServerVariables 大全

Request.ServerVariables("Url")返回服务器地址Request.ServerVariables("Path_Info")客户端提供的路...

python操作Kafka

目录一、python操作kafka1.python使用kafka生产者2.python使用kafka消费者3.使用docker中的kafka二、python操作kafka细...

Runtime.getRuntime().exec详解

Runtime.getRuntime().exec详解概述Runtime.getRuntime().exec用于调用外部可执行程序或系统命令,并重定向外部程序的标准输入、标准输出和标准错误到缓冲池。...

promise.all详解 promise.all是干什么的
promise.all详解 promise.all是干什么的

promise.all详解promise.all中所有的请求成功了,走.then(),在.then()中能得到一个数组,数组中是每个请求resolve抛出的结果...

2024-10-24 16:21 citgpt

Content-Length和Transfer-Encoding详解
  • Content-Length和Transfer-Encoding详解
  • Content-Length和Transfer-Encoding详解
  • Content-Length和Transfer-Encoding详解
  • Content-Length和Transfer-Encoding详解

取消回复欢迎 发表评论: