| 
 
| 复制代码package com.heima.test8;
public class LuckyMoney {
        /**
         * @param args
         */
        public static void main(String[] args) {
                Money m = new Money(20, 5);
                new Money("张三").start();
                new Money("李四").start();
                new Money("王五").start();
                new Money("赵六").start();
                new Money("孙七").start();
                new Money("楼主").start();
                new Money("二楼").start();
        }
}
class Money extends Thread {
        private static int totalAmount; // 红包总金额
        private static int num; // 红包个数
        public Money(String name) {
                super(name);
        }
        // 构造方法
        public Money(int totalAmount, int num) {
                this.totalAmount = totalAmount;
                this.num = num;
        }
        public void run() {
                synchronized (Money.class) {
                        try {
                                Thread.sleep(100);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        int maxMoney = totalAmount - num - 1; // 设置最大开枪红包金额
                        if (num == 1) { // 如果只剩一个红包,输出剩余的红包金额
                                System.out.println(getName() + "抢到了" + totalAmount + "元");
                                totalAmount = 0;
                                num = -1;
                        } else if (num == -1) { // 如果红包都被领完,提示抢光了
                                System.out.println(getName() + "你来晚啦,红包被抢完了");
                        } else { // 如果有红包,则随机抢到红包金额
                                int getMoney;
                                getMoney = (int) (Math.random() * maxMoney) + 1;
                                System.out.println(getName() + "抢到了" + getMoney + "元");
                                totalAmount -= getMoney; // 抢完红包金额减少
                                num--; // 抢完红包数减少
                        }
                }
        }
}
测试了几次,好像先强优势比较大,大神帮我分析一下,怎么改进
 | 
 |