效果:
代码:
public class TestDemo {
public static void main(String[] args) {
MyRunnable.setRedPackage(100, 3);
System.out.println("红包总额 " + MyRunnable.originRedPackage.remainMoney + " 红包总个数 " + MyRunnable.originRedPackage.remainSize);
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 java.math.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) {
originRedPackage.remainMoney = BigDecimal.valueOf(totalMoney);
originRedPackage.remainSize = totalSize;
}
public static synchronized BigDecimal getRandomMoney(boolean isRound, int scale) {
if (originRedPackage.remainSize == 0) {
return new BigDecimal(0);
}
if (originRedPackage.remainSize == 1) {
originRedPackage.remainSize--;
if (isRound) {
return originRedPackage.remainMoney.setScale(0, BigDecimal.ROUND_DOWN);
} else {
return originRedPackage.remainMoney.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.valueOf(originRedPackage.remainSize).divide(new BigDecimal(2), BigDecimal.ROUND_UP);
BigDecimal max1 = originRedPackage.remainMoney.divide(halfRemainSize, BigDecimal.ROUND_DOWN);
BigDecimal minRemainAmount = min.multiply(BigDecimal.valueOf(originRedPackage.remainSize - 1)).setScale(scale, BigDecimal.ROUND_DOWN);
BigDecimal max2 = originRedPackage.remainMoney.subtract(minRemainAmount);
BigDecimal max = (max1.compareTo(max2) < 0) ? max1 : max2;
BigDecimal money = random.multiply(max).setScale(scale, BigDecimal.ROUND_DOWN);
money = money.compareTo(min) < 0 ? min: money;
originRedPackage.remainSize--;
originRedPackage.remainMoney = originRedPackage.remainMoney.subtract(money).setScale(scale, BigDecimal.ROUND_DOWN);;
return money;
}
@Override
public void run() {
System.out.println("线程 " + Thread.currentThread().getId() + " 抢到了 " + getRandomMoney(false, 1) + " 元红包");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}