java实现万人抢一张火车票

一万人,同时抢一张火车票

public class TicketMain {

	//拿到火车票的线程名
	public static String getTicketThread;
	//拿到火车票的线程数
	public static volatile AtomicInteger getTicketThreadNum = new AtomicInteger(0);
	//火车票数
	public static volatile int ticketNum = 1;
	
	public static int poolSize = 10000;
	//CyclicBarrier模拟一万人同时抢票的场景
	public static CyclicBarrier cb = new CyclicBarrier(poolSize);
	//有多少张火车票,就允许多少个线程并发运行
	public static final Semaphore s = new Semaphore(ticketNum);
	static class Ticket implements Runnable {
		public void run() {
			try {
				Thread.sleep((long)(4000* Math.random()));
				System.out.println(Thread.currentThread().getName()+"-------------------------begin");
				cb.await();
				s.acquire();
				if(ticketNum <= 0) {
					return ;
				}
				ticketNum--;
				getTicketThread = Thread.currentThread().getName();
				getTicketThreadNum.incrementAndGet();
				System.out.println(Thread.currentThread().getName() + " get ticket................................................");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			} finally {
				s.release();
				System.out.println(Thread.currentThread().getName()+"-------------------------end");
			}
		}


	}
	
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
		for(int i = 0; i < poolSize; i++) {
			threadPool.execute(new Ticket());
		}
		threadPool.shutdown();
		while(!threadPool.isTerminated()) {
		}
		try {
			Thread.sleep(1000);
			System.out.println("getTicketThread:" + getTicketThread + ", getTicketNum:" + getTicketThreadNum.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}


}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值