java抢红包,写个多线程程序
时间: 2024-04-16 09:22:25 浏览: 49
java采用多线程实现抢红包程序完整源码
Java抢红包是一个常见的多线程编程问题,下面是一个简单的示例程序:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedPacket {
private double totalAmount; // 红包总金额
private int totalNum; // 红包总数量
private List<Double> amounts; // 每个红包的金额
public RedPacket(double totalAmount, int totalNum) {
this.totalAmount = totalAmount;
this.totalNum = totalNum;
this.amounts = new ArrayList<>();
}
public synchronized double grab() {
if (totalNum <= 0) {
return 0;
}
if (totalNum == 1) {
totalNum--;
return totalAmount;
}
Random random = new Random();
double max = totalAmount / totalNum * 2;
double amount = random.nextDouble() * max;
amount = amount < 0.01 ? 0.01 : amount;
totalAmount -= amount;
totalNum--;
amounts.add(amount);
return amount;
}
public static void main(String[] args) {
double totalAmount = 100; // 红包总金额
int totalNum = 10; // 红包总数量
RedPacket redPacket = new RedPacket(totalAmount, totalNum);
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < totalNum; i++) {
Thread thread = new Thread(() -> {
double amount = redPacket.grab();
System.out.println(Thread.currentThread().getName() + " 抢到了 " + amount + " 元");
});
threads.add(thread);
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("红包抢完了");
}
}
```
上述程序中,`RedPacket`类表示一个红包,通过`synchronized`关键字保证了抢红包的线程安全性。`grab`方法用于抢红包,每个线程调用该方法可以获取一个随机金额的红包。在`main`方法中,创建了10个线程来同时抢红包,最后输出每个线程抢到的金额。
阅读全文