多线程模拟火车站卖票-继承Thread类

public class Demo2_Snschronized {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("多线程开始时间(毫秒):"+System.currentTimeMillis());
    new Ticket().start();
    new Ticket().start();
    new Ticket().start();
    new Ticket().start();

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < 100000; i++) {
      System.out.print("");
    }
    System.out.println("单线程卖票结束。。。。。。。。。。。。。。。");
    endTime = System.currentTimeMillis();
    System.out.println("单线程售卖100000张票,共计用时:"+(endTime-startTime)+"毫秒!");
  }

}

class Ticket extends Thread{
  private static int ticket = 100000;
  public void run() {
    synchronized (Ticket.class) {
      while(ticket>0) {
        // System.out.println((ticket--)+"号票已售出!");
        ticket--;
      }    
      if(ticket==0) {
        System.out.println("多线程卖票结束。。。。。。。。。。。。");
        System.out.println("多线程结束时间(毫秒):"+System.currentTimeMillis());
      }
    }
  }
}

posted @ 2019-03-12 16:33  幻音坊-女帝  阅读(350)  评论(0编辑  收藏  举报