package mypackage;
import java.util.ArrayList;
import java.util.List;
/**
* 给定一个金额,指定红包个数,随机分拆红包组成list
* 采用多线程抽取红包
* 注意同步加锁
* 注意随机红包list得派发,判断条件
*/
//红包金额为acoout,随机拆分成count个。
class RandomHbao {
int acount;
int count;
public RandomHbao(int acount, int count) {
this.acount = acount;
this.count = count;
}
// 随机拆分方法
public List<Integer> sample() {
// 创建一个list容器
List<Integer> list = new ArrayList<Integer>();
while (true) {
// 随机产生一个红包的金额,为整数
// Math.random()产生一个数,范围[0,1),注意前闭区后开
// Math.random() * acount范围[0,acount)
// Math.random() * acount + 1范围[1,acount+1)
// (int)(Math.random() * acount + 1)范围[1,acount],注意前闭后闭
int hbao1 = (int) (Math.random() * acount + 1);
// 如果剩下人均金额大于1且发的红包金额小于等于20且不是最后一个红包,就将这个随机红包放入list
// 并且总金额减去剩下的红包,求得剩下得金额,剩下得红包数
if (((acount - hbao1) / (count-1) >= 1) & (hbao1 <= 20) & (count > 1)) {
list.add(hbao1);
acount -= hbao1;
count--;
//如果是最后一个红包,直接等于剩下得金额即可,并退出循环
if (count == 1) {
list.add(acount);
acount = 0;
break;
}
}
// 否则得话,说明随机得红包不行,得从新循环,分配红包
else {
continue;
}
}
// 得到最后得随机红包list
return list;
}
}
//发红包线程,从红包list中随机选取出来
class Gethbao implements Runnable {
// 实例化,得到随机红包list
RandomHbao randomhbao=new RandomHbao(100,10);
List<Integer> sample=randomhbao.sample();
@Override
public void run() {
// 注意使用同步代码块,这里同步对象选择sample,因为后面得操作要修改得sample
synchronized (sample){
// 随机索引
int index=(int) (Math.random() *sample.size());
System.out.println(Thread.currentThread().getName()+ "获得红包"+sample.get(index)+"元");
// 发出一个就删除这个红包
sample.remove(index);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args){
Gethbao h=new Gethbao();
// 创建10个线程并启动
for (int i=1;i<=10;i++){
Thread t=new Thread(h);
t.start();
}
}
}
结果如下: