面向对象程序的设计题

实现一个模拟的列车售票系统用六个窗口出售500张车票打印处每个售票窗口的出票号码和出票时间


import java.util.Date;

public class Ticket implements Runnable{

    //车票的数量
    int count=500;

    @Override
    public void run() {
        while(count>0) {
            try {
                /*同步:synchronized(锁),锁就是一个对象名称,通常可以直接传this
                 * 在同步语句块中的语句,确保在同一时刻只能由一个线程执行(互斥)
                 * */
                synchronized (this) {
                    System.out.println("窗口名称:"+Thread.currentThread().getName()+",车票编号:"+count+",销售时间:"+ new Date().toLocaleString());
                    count--;

                }
                Thread.sleep(10);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public class TicketTest {

    public static void main(String[] args) {
        
        Ticket ticket = new Ticket();
        //模拟4个售票窗口
        Thread t1 = new Thread(ticket,"窗口1:");
        Thread t2 = new Thread(ticket,"窗口2:");
        Thread t3 = new Thread(ticket,"窗口3:");
        Thread t4 = new Thread(ticket,"窗口4:");
        Thread t5 = new Thread(ticket,"窗口5:");
        Thread t6 = new Thread(ticket,"窗口6:");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }
}

自己的作业自己做

实现代码,线程实现

public class SaleTicket implements Runnable {
  int tickets = 500;

  @Override
  public void run() {
    while (tickets > 0) {
      sale();
    }
  }

  public synchronized void sale() {
    if (tickets > 0) {
      // 打印第几个线程正在执行
      String name = Thread.currentThread().getName();
      String timeStr =
          LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
      int i = 500 - tickets + 1;
      System.out.println(name + "卖第" + i + "张票, " + "出票码: K" + i + ", 出票时间: " + timeStr);
      tickets--;
       
    }
  }
}

public class TestSaleTicket {
    public static void main(String[] args) {
        SaleTicket st = new SaleTicket();
        Thread thread = new Thread(st, "一号窗口");
        Thread thread1 = new Thread(st, "二号窗口");
        Thread thread2 = new Thread(st, "三号窗口");
        Thread thread3 = new Thread(st, "四号窗口");
        Thread thread4 = new Thread(st, "五号窗口");
        Thread thread5 = new Thread(st, "六号窗口");

        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

运行结果:

img

img

img