1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package qianghongbao; import java.util.Random; public class HongBao { private double remainMoney; //剩余的钱 private int remainSize; //剩余的红包数量 public HongBao(double total, int count) { this.remainMoney = total; this.remainSize = count; } public double getRemainMoney() { return remainMoney; } public int getRemainSize() { return remainSize; } public double getRandomMoney(){ double money; if(remainSize == 1){ remainSize--; money = (double)Math.round(remainMoney * 100 )/100; } else if(remainSize > 1){ double min = 0.01; double max = remainMoney / remainSize * 2; money = new Random().nextDouble() * max; money = money <= min ? min : money; money = Math.floor(money * 100) / 100; remainSize--; remainMoney -= money; } else { money = 0; } // System.out.println(Thread.currentThread().getName()+ // "抢到"+money+"元,红包剩余"+remainSize+"个"); return money; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package qianghongbao; public class UserThread implements Runnable{ private HongBao hongBao; private double max = -1; String king = null; public UserThread(HongBao hongBao) { this.hongBao = hongBao; } public String getKing() { return king; } @Override public void run() { synchronized (this){ double money = hongBao.getRandomMoney(); if(money > max){ max = money; king = Thread.currentThread().getName(); } if(money == 0) { System.out.println("时刻"+System.currentTimeMillis()+","+ Thread.currentThread().getName() + ":你们是坐在路由器上抢的吗!"); } else { System.out.println("时刻"+System.currentTimeMillis()+","+ Thread.currentThread().getName() + ":抢到 " + money + "元,红包剩余"+hongBao.getRemainSize()+"个"); } } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package qianghongbao; import java.util.Scanner; public class QiangHongBao { public static void main(String[] args) throws InterruptedException{ System.out.println("请输入红包金额红包个数"); Scanner sc = new Scanner(System.in); double total = sc.nextDouble(); int count = sc.nextInt(); HongBao hongBao =new HongBao(total,count); UserThread user = new UserThread(hongBao); System.out.println("请输入模拟抢红包人数"); int num = sc.nextInt(); for(int i=0;i<num;i++) { new Thread(user).start(); } Thread.sleep(3000); System.out.println("运气王:"+user.getKing()); sc.close(); } }
-------------
Thank you for reading
-------------