zoukankan      html  css  js  c++  java
  • 模拟售火车票 多线程


    100张票,10个窗口(10个线程模拟),实现线程卖票计数



    import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class SellTicket implements Runnable { private int count = 100; static Map<String,Integer> map = new ConcurrentHashMap<String,Integer>(); public static void main(String[] args) { SellTicket st = new SellTicket(); for (int i = 0; i < 10; i++) { Thread thread = new Thread(st); map.put(thread.getName(), 0); thread.start(); } } @Override public void run() { while (true) { synchronized(this){ if(count > 0){ count--; System.out.println("线程=" + Thread.currentThread().getName() + ";剩余票数=" + count); Iterator<Map.Entry<String,Integer>> i = map.entrySet().iterator(); while(i.hasNext()){ Map.Entry<String,Integer> entry=(Map.Entry<String,Integer>)i.next(); if(entry.getKey().equals(Thread.currentThread().getName())) map.put(entry.getKey(), entry.getValue().intValue() + 1); } }else if(count==0){ Iterator<Map.Entry<String,Integer>> i = map.entrySet().iterator(); while(i.hasNext()){ Map.Entry<String,Integer> entry=(Map.Entry<String,Integer>)i.next(); System.out.println("线程=" + entry.getKey() + ";卖票数=" + entry.getValue()); } } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }

      

  • 相关阅读:
    2018-4-17-软件设计-白话依赖注入
    2018-2-13-wpf-PreviewTextInput-在鼠标输入获得-_u0003
    2018-5-23-为何-987654321_123456789-的值是-8.0000000729
    寄存器位写操作
    Linux多IP配置
    Kconfig和Makefile
    linux设置网卡速率
    Winmanager,NERDTree和MiniBufExplorer
    SuperTab
    ping
  • 原文地址:https://www.cnblogs.com/evilrogue/p/2856531.html
Copyright © 2011-2022 走看看