Java实现抢红包
效果:
代码:
public class TestDemo {
public static void main(String[] args){
java valueofMyRunnable.setRedPackage(100,3);
System.out.println("红包总额 "+ ainMoney +" 红包总个数 "+ ainSize)
MyRunnable myRunnable =new MyRunnable();
Thread thread =new Thread(myRunnable);
Thread thread1 =new Thread(myRunnable);
Thread thread2 =new Thread(myRunnable);
Thread thread3 =new Thread(myRunnable);
thread.start();
thread1.start();
thread2.start();
thread3.start();
}
}
import BigDecimal;
public class MyRunnable implements Runnable {
public static RedPackage originRedPackage =new RedPackage();
static class RedPackage {
int remainSize;
BigDecimal remainMoney;
}
public static void setRedPackage(int totalMoney,int totalSize){
}
public static synchronized BigDecimal getRandomMoney(boolean isRound,int scale){
// isRound红包⾦额是否整数
// scale红包⾦额保留⼏位⼩数
// remainSize 剩余的红包数量
// remainMoney 剩余的钱
ainSize ==0){
return new BigDecimal(0);
}
ainSize ==1){
if(isRound){
if(isRound){
ainMoney.setScale(0, BigDecimal.ROUND_DOWN);
}else{
ainMoney.setScale(scale, BigDecimal.ROUND_DOWN);
}
}
BigDecimal random = BigDecimal.valueOf(Math.random());
double minTemp;
if(isRound){
minTemp =0;
}else{
minTemp =0.01;
}
BigDecimal min = BigDecimal.valueOf(minTemp);
BigDecimal halfRemainSize = BigDecimal.ainSize).divide(new BigDecimal(2), BigDecimal.ROUND_UP);
BigDecimal max1 = ainMoney.divide(halfRemainSize, BigDecimal.ROUND_DOWN);
BigDecimal minRemainAmount = min.multiply(BigDecimal.ainSize -1)).setScale(scale, BigDecimal.ROUND_DOWN BigDecimal max2 = ainMoney.subtract(minRemainAmount);
BigDecimal max =(max1pareTo(max2)<0)? max1 : max2;
BigDecimal money = random.multiply(max).setScale(scale, BigDecimal.ROUND_DOWN);
money = moneypareTo(min)<0? min: money;
return money;
}
@Override
public void run(){
System.out.println("线程 "+ Thread.currentThread().getId()+" 抢到了 "+getRandomMoney(false,1)+" 元红包");
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论