我是这么写的,你参考下
- public class Test7 {
- public static void main(String[] args) {
-
- //创建SealWindow对象
- SealWindow sw=new SealWindow();
-
- //创建并开启四个线程
- new Thread(sw,"窗口一").start();
- new Thread(sw,"窗口二").start();
- new Thread(sw,"窗口三").start();
- new Thread(sw,"窗口四").start();
- }
- }
- //模拟售票中心功能属性
- class TicketSealCenter
- {
-
- //售票中心唯一,单例设计
- private static TicketSealCenter instance=new TicketSealCenter();
- TicketSealCenter(){}
- public static TicketSealCenter getInstance()
- {
- return instance;
- }
- //售票中心具有统一发票功能
- private Ticket ticket=new Ticket();
- public int getTickets()
- {
- return ticket.generateTickets();
- }
- }
- //模拟售票窗口,由于是几个窗口同时买票,多线程对象应该是窗口
- class SealWindow implements Runnable
- {
- //获取售票中心发放的火车票
- private int tickets=TicketSealCenter.getInstance().getTickets();
-
- //定义任意一个对象,并做同步代码块的锁
- Object lock=new Object();
- public void run()
- {
- while(true)
- {
- //定义同步代码块
- synchronized(lock)
- {
-
- //经过的线程休眠10s
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
-
- //输出售票信息
- if(tickets>0)
- {
- System.out.println(Thread.currentThread().getName()+"正在发售第"+tickets--+"张票");
- }
- else
- {
- break;
- }
- }
- }
- }
- }
- //模拟火车票应有属性及方法
- class Ticket
- {
- //车票的属性有车厢号和座位号,num1代表车厢号,num2代表座位号
- int num1=1;
- int num2=100;
- public String getMessage()
- {
- return "车厢号:"+num1+"座位号:"+num2;
- }
- public int generateTickets()
- {
- return num2;
- }
-
- }
复制代码 |