这是入学考试时自己抽到的题目,跟大家分享一下,编写三个类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。代码实现如下:- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- public class SealTicketsDemo {
- /**
- * @param args
- * 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
- * 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
- */
- public static void main(String[] args) {
- Thread t1=new Thread(new SealWindows());
- t1.setName("1号窗口");
- Thread t2=new Thread(new SealWindows());
- t2.setName("2号窗口");
- Thread t3=new Thread(new SealWindows());
- t3.setName("3号窗口");
- Thread t4=new Thread(new SealWindows());
- t4.setName("4号窗口");
- Thread t5=new Thread(new SealWindows());
- t5.setName("5号窗口");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- }
- //票信息
- class Ticket{
- private int id;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
-
- }
- //售票窗口
- class SealWindows implements Runnable{
- @Override
- public void run() {
- // TODO Auto-generated method stub
- SealTickets();
- }
- public static void SealTickets(){
- TicketSealCenter tsc=TicketSealCenter.getInstance();
- List<Ticket>tickets=tsc.getTickets();
- while(!tickets.isEmpty()){
- synchronized(tickets){
- if(tickets.isEmpty())
- break;
- Iterator<Ticket>iterator=tickets.iterator();
- try {
- Thread.sleep(100);
- } catch (Exception e) {
- // TODO: handle exception
- }
- Ticket ticket=iterator.next();
- System.out.println(Thread.currentThread().getName()+"...卖了一张票,ID为:"+ticket.getId());
- tickets.remove(ticket);
- }}
- }
-
-
- }
- //售票中心,将其设置成单例模式
- class TicketSealCenter{
- private List<Ticket>tickets=new ArrayList<Ticket>();
- private int ticketNum=50;
- private static TicketSealCenter tsc=new TicketSealCenter();
- private TicketSealCenter(){
- setIDToTicket(tickets);
- }
- //为每一张票设置ID编号
- public void setIDToTicket(List<Ticket>tickets){
- for(int i=1;i<=ticketNum;i++){
- Ticket ticket=new Ticket();
- ticket.setId(i);
- tickets.add(ticket);
- }
- }
- public static TicketSealCenter getInstance(){
- return tsc;
- }
- public List<Ticket>getTickets(){
- return tickets;
- }
- }
复制代码 |
|