欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-27 08:33:58
大体思路红包的分发见java作业——红包分发。而抢红包要解决的是线程问题。其实比较简单,设定好人数,每个人一个线程,每个线程执行一遍,有红包就抢,没有红包就抢不到,所以run函数中只要判断现在还有没有...

大体思路

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

代码实现

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多线程抢红包内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: JAVA 抢红包