售票员售票-阿里算法题(感觉我又被撸了)

题目

有1000张票(0~999),初始每张票售价500元,每卖掉一张剩余的每张票涨100元。有三个售票员同时售票,设计一个算法计算出每个售票员卖的票和赚的钱。

1:售票员卖完一张可以立即卖第二张,第三张.....

2:需要同时开始售票

解题

通过AtomicInteger来计算剩余的票,利用他的原子性,避免枷锁

通过AtomicBoolean来设置何时开始卖,如果没有这个的话,三个线程先后启动,越先启动的线程就会越先卖票

不可使用Synchronized来做加锁,因为某个售票员可以随时买票,不可中断

通过Thread.yiels()方法让某个线程暂时让出CPU而不是用wait等

public class WhoSellMoreTicket {

  public static void main(String[] args) throws InterruptedException {
    sellTickets();
  }

  public static final AtomicInteger allTicket = new AtomicInteger(1000);
  public static final int ORIGIN_PRICE = 500;

  public static final AtomicBoolean startSell = new AtomicBoolean(false);

  public static void sellTickets() throws InterruptedException {
    Thread sellMan1 = new Thread(new Runnable() {
      @Override
      public void run() {
        sellTicketAndColleckInfo("sellMan1");
      }
    });

    Thread sellMan2 = new Thread(new Runnable() {
      @Override
      public void run() {
        sellTicketAndColleckInfo("sellMan2");
      }
    });

    Thread sellMan3 = new Thread(new Runnable() {
      @Override
      public void run() {
        sellTicketAndColleckInfo("sellMan3");
      }
    });

    sellMan1.start();
    sellMan2.start();
    sellMan3.start();

    startSell.compareAndSet(false, true);
    sellMan1.join();
    sellMan2.join();
    sellMan3.join();


  }

  private static void sellTicketAndColleckInfo(String sellMan1) {
    int allMoney = 0;
    List allSellTicket = new ArrayList<>();
    while (!startSell.get()) {
      Thread.yield();
    }
    while (allTicket.get() > 0) {
      int curTicketNo = allTicket.decrementAndGet();
      if (curTicketNo < 0) {
        return;
      }
      allSellTicket.add(curTicketNo);
      allMoney += ORIGIN_PRICE + (10 - (curTicketNo / 100 + 1)) * 100;
      Thread.yield();
    }
    System.out.println("sellMan:" + sellMan1 + ",allSellTicket:" + allSellTicket + ",allMoney:" + allMoney);
  }
}

这题是阿里的算法题,感觉有点简单,可能是人家没看上我,随便出了道题吧

你可能感兴趣的:(算法,算法,java,多线程,原子类)