Thread并发问题、实现三个窗口同时售票、
1 package com.zhiqiang.server.basic.thread; 2 3 /** 4 * @Description: 功能:用三个线程模拟三个售票口,总共200张票 5 * @Author: zzq 6 * @CreateDate: 7 */ 8 public class ThreadTestDemo { 9 public static void main(String[] args) { 10 TicketSales sales = new TicketSales(); 11 new Thread(sales).start(); 12 new Thread(sales).start(); 13 new Thread(sales).start(); 14 } 15 } 16 17 class TicketSales implements Runnable { 18 Ticket ticket = new Ticket(20); 19 20 @Override 21 public void run() {
//当这里剩下一张票的时候,三个线程可能会同时 拿到最后一张票,就会出现如下运行结果: 22 while (ticket.getTickets() > 0) { 23 synchronized (ticket) { 24 System.out.println(Thread.currentThread().getName() + " 卖出一张,还剩: " + (ticket.getTickets() - 1)); 25 try { 26 ticket.setTickets(ticket.getTickets() - 1); 27 Thread.sleep(1); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 } 32 } 33 } 34 } 35 36 class Ticket { 37 //总票数 38 private int tickets; 39 40 public Ticket() { 41 } 42 43 public Ticket(int num) { 44 this.tickets = num; 45 } 46 47 public int getTickets() { 48 return tickets; 49 } 50 51 public void setTickets(int tickets) { 52 this.tickets = tickets; 53 } 54 }
解决方案就是在买票前判断: 如果票<=0 , 则提示票已经卖完:
运行结果: