JAVA多线程抢红包的实现示例

时间:2022-09-25 00:20:28

大体思路

红包的分发见JAVA作业——红包分发。
而抢红包要解决的是线程问题。
其实比较简单,设定好人数,每个人一个线程,每个线程执行一遍,有红包就抢,没有红包就抢不到,所以run函数中只要判断现在还有没有红包就可以了。

代码实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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多线程抢红包的实现示例的文章就介绍到这了,更多相关JAVA多线程抢红包内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Evrse/article/details/112105591