这篇文章给大家介绍怎么在JAVA中利用多线程抢红包,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { int person_num, red_pocket_num, sum_money; Scanner scanner = new Scanner(System.in); System.out.println("请设置红包个数:"); red_pocket_num = scanner.nextInt(); System.out.println("请设置总金额数量(分):"); sum_money = scanner.nextInt(); if(sum_money < red_pocket_num) { System.out.println("钱不够,退出程序。"); return; } System.out.println("请设置抢红包成员个数:"); person_num = scanner.nextInt(); myRunnable myrunnable = new myRunnable(sum_money,red_pocket_num); Thread []person = new Thread[person_num]; for (int i = 0; i < person_num; i++) { person[i] = new Thread(myrunnable); person[i].setName("用户"+(i+1)); person[i].start(); } } } class myRunnable implements Runnable{ private int []red_pocket; private int num; private int now_num; public myRunnable(int money, int num) { this.red_pocket = new Red_Pocket(money, num).get_red_packets(); this.num = num; this.now_num = num; } @Override public void run() { if(this.num>0){ System.out.println(Thread.currentThread().getName()+"抢到了红包 "+(this.num-this.now_num+1)+" : "+red_pocket[--this.now_num]+"分"); } else{ System.out.println(Thread.currentThread().getName()+"未抢到红包。"); } } } class Red_Pocket{ private long seed; private int money; private int num; public int[] get_red_packets() { if(this.money < this.num) return new int[0]; Random random = new Random(this.seed); this.seed = random.nextLong(); int[] res = new int[this.num]; double[] temp = new double[this.num]; double sum = 0; int sum2 = 0; for (int i = 0; i < this.num; i++) { temp[i] = random.nextDouble(); sum += temp[i]; } for (int i = 0; i < this.num; i++) { res[i] = 1 + (int)(temp[i] / sum * (this.money - this.num)); sum2 += res[i]; } res[random.nextInt(this.num)] += this.money - sum2; return res; } private void init() { this.seed = new Random(System.currentTimeMillis()).nextLong(); } public Red_Pocket(int money,int num) { init(); this.money = money; this.num = num; } }
关于怎么在JAVA中利用多线程抢红包就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。