模拟彩票程序,有一个抽奖池,里面有100000张彩票,每张彩票有编号(6位数字组成,不能重复),中奖金额,全国有500个彩票购买点,每个购买点卖出150张彩票,用进程的同步,保证购买彩票不能重复,随机生成10个中奖号码,显示彩票的中奖情况。写出以上Java代码并详细注释
时间: 2024-11-13 13:28:05 浏览: 34
在Java中编写模拟彩票程序,我们需要创建一个彩票类,定义彩票的基本属性,以及线程安全的购买彩票和中奖号码生成等功能。这里是一个简单的示例,使用了`java.util.concurrent`包来实现并发和同步:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
// 定义彩票类
class LotteryTicket {
private int id; // 彩票编号
private double prize; // 中奖金额
private boolean isWinning; // 是否中奖
public LotteryTicket(int id, double prize) {
this.id = id;
this.prize = prize;
this.isWinning = false;
}
// 获取彩票信息
@Override
public String toString() {
return "ID: " + id + ", Prize: " + prize + ", IsWinning: " + isWinning;
}
}
// 抽奖池类
class LotteryPool {
private static final int TOTAL_TICKETS = 100000;
private List<LotteryTicket> tickets = new ArrayList<>();
public void initialize() {
for (int i = 0; i < TOTAL_TICKETS; i++) {
LotteryTicket ticket = new LotteryTicket(i, generatePrize());
tickets.add(ticket);
}
Collections.shuffle(tickets); // 随机排列彩票
}
private double generatePrize() {
// 省略中奖概率计算部分
return Math.random(); // 这里仅作为示例,实际应根据规则生成不同金额
}
// 同步购买彩票
synchronized public void buyTicket(int purchasePoint, int numTickets) {
if (numTickets <= tickets.size()) {
for (int i = 0; i < numTickets; i++) {
if (!tickets.isEmpty()) {
LotteryTicket ticket = tickets.remove(0);
System.out.println("Purchase Point " + purchasePoint + ": Bought Ticket ID: " + ticket.id);
} else {
break;
}
}
} else {
throw new IllegalArgumentException("Number of tickets exceeds available tickets");
}
}
// 公布中奖号码
public synchronized void announceWinners(List<Integer> winningNumbers) {
for (LotteryTicket ticket : tickets) {
if (winningNumbers.contains(String.valueOf(ticket.id))) {
ticket.isWinning = true;
System.out.println("Ticket ID " + ticket.id + " is a winner!");
}
}
}
}
public class Main {
public static void main(String[] args) {
LotteryPool lotteryPool = new LotteryPool();
lotteryPool.initialize();
// 创建500个购买点
for (int i = 1; i <= 500; i++) {
Thread purchaseThread = new Thread(() -> {
lotteryPool.buyTicket(i, 150);
});
purchaseThread.start();
}
// 生成10个中奖号码并宣布
List<Integer> winningNumbers = generateWinningNumbers(10);
lotteryPoolannounceWinners(winningNumbers);
// 保证所有购买完成后再展示剩余未中奖彩票
while (!lotteryPool.tickets.isEmpty()) {
System.out.println("Remaining Tickets:");
for (LotteryTicket ticket : lotteryPool.tickets) {
System.out.println(ticket);
}
}
}
private static List<Integer> generateWinningNumbers(int num) {
Random random = new Random();
List<Integer> winners = new ArrayList<>();
for (int i = 0; i < num; i++) {
winners.add(random.nextInt(TOTAL_TICKETS));
}
return winners;
}
}
```
在这个示例中,我们首先初始化彩票池,然后创建500个购买点的线程分别购买彩票。同时,我们生成10个中奖号码,并在主函数结束前检查是否有未售出的彩票。注意,这里简化了购票过程,实际应用中需要更复杂的错误处理和同步机制。
阅读全文