我用java写的抢红包用的红包类,支持多线程

import java.util.concurrent.atomic.AtomicInteger;

public class CashGift {
	public static class OverException extends Exception {
		
	}
	private final int totalNumber;
	private final float totalMoney;
	private final AtomicInteger index = new AtomicInteger();
	long p1, p2, p3, p4, p5, p6, p7;
	private volatile int realIndex;
	private volatile float remainMoney;
	public CashGift(int totalNumber, float totalMoney) {
		this.totalNumber = totalNumber;
		this.totalMoney = totalMoney;
		realIndex = 1;
		remainMoney = totalMoney;
	}
	protected float rand(float x) {
		return (float)(Math.random() * x);
	}
	protected float getMoney(int i) {
		if (i < totalNumber) {
			float j = totalNumber + 1 - i;
			return rand(2 / j) * remainMoney * j / 2;
		} else {
			return remainMoney;
		}
	}
	
	public float get() throws OverException {
		int ticket = index.incrementAndGet();
		if (ticket > totalNumber) {
			throw new OverException();
		} else {
			for (;;) {
				if (ticket == realIndex) {
					float money = getMoney(realIndex);
					remainMoney -= money;
					realIndex++;
					return money;
				}
			}
		}
	}
}

测试代码,8G内存,Xeon E5-2630处理器,以下测试代码跑的时间为15155466407ns。

final CashGift[] cgList = new CashGift[10000];
for (int i = 0; i < cgList.length; i++) {
	cgList[i] = new CashGift(100, 10000);
}	
Runnable qianghongbao = new Runnable() {

	@Override
	public void run() {
		int i = 0;
		while (i < cgList.length) {
			try {
				cgList[i].get();
			} catch(CashGift.OverException e) {
				i++;
			}
		}
	}
};
System.out.println("Starting...");
int number = 100;
final Thread[] people = new Thread[number];
long start = System.nanoTime();
for (int i = 0; i < people.length; i++) {
	people[i] = new Thread(qianghongbao);
	people[i].start();
}
for (int i = 0; i < people.length; i++) {
	people[i].join();
}
System.out.println(System.nanoTime() - start);
int i;
for (i = 0; i < cgList.length; i++) {
	if (!cgList[i].isEmpty()) {
		System.out.println("Failed!");
		break;
	}
}
if (cgList.length == i)
	System.out.println("Successed!");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值