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

32次阅读

共计 10344 个字符,预计需要花费 26 分钟才能阅读完成。

写在前面

  • 把技术概念通过文字的形式写下来,理清逻辑,加深认知;
  • 把知识点通过系列文章的形式分段写下来,让思维进行刻意的训练;
  • 把难懂的东西通过有趣的故事或者例子讲出来,让技术变得生动。

电影票的案例

单线程的例子

我们设定有一个电影院,该电影院开张不久,在入口的旁边只设立了一个售票点 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);

写在最后

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

正文完
 0