JAVA多線程搶紅包的實現(xiàn)示例
紅包的分發(fā)見JAVA作業(yè)——紅包分發(fā)。而搶紅包要解決的是線程問題。其實比較簡單,設定好人數,每個人一個線程,每個線程執(zhí)行一遍,有紅包就搶,沒有紅包就搶不到,所以run函數中只要判斷現(xiàn)在還有沒有紅包就可以了。
代碼實現(xiàn)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多線程搶紅包的實現(xiàn)示例的文章就介紹到這了,更多相關JAVA多線程搶紅包內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. 學python最電腦配置有要求么2. Spring security 自定義過濾器實現(xiàn)Json參數傳遞并兼容表單參數(實例代碼)3. JAMon(Java Application Monitor)備忘記4. Java8內存模型PermGen Metaspace實例解析5. python中用Scrapy實現(xiàn)定時爬蟲的實例講解6. 基于python實現(xiàn)操作git過程代碼解析7. python使用QQ郵箱實現(xiàn)自動發(fā)送郵件8. Python Scrapy多頁數據爬取實現(xiàn)過程解析9. 解決redis與Python交互取出來的是bytes類型的問題10. Python 的 __str__ 和 __repr__ 方法對比
