国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

JAVA多線程搶紅包的實(shí)現(xiàn)示例

瀏覽:52日期:2022-08-15 09:19:01
大體思路

紅包的分發(fā)見(jiàn)JAVA作業(yè)——紅包分發(fā)。而搶紅包要解決的是線程問(wèn)題。其實(shí)比較簡(jiǎn)單,設(shè)定好人數(shù),每個(gè)人一個(gè)線程,每個(gè)線程執(zhí)行一遍,有紅包就搶?zhuān)瑳](méi)有紅包就搶不到,所以run函數(shù)中只要判斷現(xiàn)在還有沒(méi)有紅包就可以了。

代碼實(shí)現(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('請(qǐng)?jiān)O(shè)置紅包個(gè)數(shù):'); red_pocket_num = scanner.nextInt(); System.out.println('請(qǐng)?jiān)O(shè)置總金額數(shù)量(分):'); sum_money = scanner.nextInt(); if(sum_money < red_pocket_num) { System.out.println('錢(qián)不夠,退出程序。'); return; } System.out.println('請(qǐng)?jiān)O(shè)置搶紅包成員個(gè)數(shù):'); 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; }}

到此這篇關(guān)于JAVA多線程搶紅包的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)JAVA多線程搶紅包內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 林西县| 老河口市| 沁源县| 大渡口区| 宁国市| 当雄县| 迁安市| 鲁甸县| 嘉黎县| 平谷区| 库伦旗| 砚山县| 清水河县| 尼玛县| 华阴市| 龙南县| 凤翔县| 奇台县| 满城县| 新干县| 会昌县| 石泉县| 历史| 驻马店市| 胶州市| 泰顺县| 南丹县| 定安县| 泰兴市| 化州市| 石台县| 长治市| 高雄市| 冕宁县| 阜城县| 青浦区| 庆阳市| 普陀区| 海原县| 阳谷县| 嘉祥县|