介绍
这篇文章给大家介绍怎么在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 扫描仪(系统); ,,,System.out.println(“请设置红包个数:“); ,,,red_pocket_num =, scanner.nextInt (); ,,,System.out.println(“请设置总金额数量(分):“); ,,,sum_money =, scanner.nextInt (); ,,,如果(sum_money & lt;, red_pocket_num), { ,,,,,System.out.println(“钱不够,退出程序!”); ,,,,,返回; ,,,} ,,,System.out.println(“请设置抢红包成员个数:“); ,,,person_num =, scanner.nextInt (); ,,,myRunnable myRunnable =, new myRunnable (sum_money red_pocket_num); ,,,Thread [] person =, new 线程(person_num); ,,,for (int 小姐:=,0;,小姐:& lt;, person_num;,我+ +),{ ,,,,,的人(我),=,new 线程(myrunnable); ,,,,,人[我].setName(“用户“+ (i + 1)); ,,,,,人[我].start (); ,,,} ,,} } class myRunnable  implements Runnable { private 才能;int [] red_pocket; private 才能;int  num; private 才能;int  now_num; public 才能myRunnable (int 钱,,int num), { ,,,this.red_pocket =, new Red_Pocket(钱,,num) .get_red_packets (); ,,,this.num =, num; ,,,this.now_num =, num; ,,} @Override才能 public 才能;void 运行(),{ ,,,如果(this.num> 0) { ,,,,,System.out.println (Thread.currentThread () . getname() +“抢到了红包,“+ (this.num-this.now_num + 1) +“,:,“+ red_pocket [——this.now_num] +“分”); ,,,} 其他,,,{ ,,,,,System.out.println (Thread.currentThread () . getname() +“未抢到红包!”); ,,,} ,,} } class Red_Pocket { private 才能long 种子; private 才能;int 资金; private 才能;int  num; public 才能,int [], get_red_packets (), { ,,,如果(this.money & lt;, this.num), return new int [0]; ,,,Random Random =, new 随机(this.seed); ,,,this.seed =, random.nextLong (); ,,,int [], res =, new int [this.num]; ,,,双[],temp =, new 双(this.num); ,,,double sum =, 0; ,,,int sum2 =, 0; ,,,for (int 小姐:=,0;,小姐:& lt;, this.num;,我+ +),{ ,,,,,临时[我],=,random.nextDouble (); ,,,,,sum +=,临时[我]; ,,,} ,,,for (int 小姐:=,0;,小姐:& lt;, this.num;,我+ +),{ ,,,,,res[我],=,1,+,(int)(临时[我],/,sum *, (this.money 作用;this.num)); ,,,,,sum2 +=, res[我]; ,,,} ,,,res (random.nextInt (this.num)], +=, this.money 作用;sum2; ,,,return res; ,,} private 才能;void  init (), { ,,,this.seed =, new 随机(System.currentTimeMillis ()) .nextLong (); ,,} public 才能;Red_Pocket (int 钱,int num), { ,,,init (); ,,,this.money =,钱; ,,,this.num =, num; ,,} }
关于怎么在JAVA中利用多线程抢红包就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。