java 多线程写一个全场篮球比赛的例子,打满四节比赛结束
时间: 2023-05-22 16:05:48 浏览: 52
这是一个非常好的编程问题。这里是一个 Java 多线程的全场篮球比赛的例子,打满四节比赛结束的实现:
```java
import java.util.concurrent.ThreadLocalRandom;
public class BasketballGame implements Runnable {
private final String team1;
private final String team2;
private final int numMaxPlayers;
private final int numQuarters;
private final int numThreads;
private int team1Score = 0;
private int team2Score = 0;
private int currentQuarter = 0;
public BasketballGame(String team1, String team2, int numMaxPlayers, int numQuarters, int numThreads) {
this.team1 = team1;
this.team2 = team2;
this.numMaxPlayers = numMaxPlayers;
this.numQuarters = numQuarters;
this.numThreads = numThreads;
}
@Override
public void run() {
while (currentQuarter < 4) {
synchronized (this) {
while (currentQuarter < 4) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
System.out.println("Quarter " + currentQuarter + " is over.\n" +
team1 + " scored " + team1Score + " points.\n" +
team2 + " scored " + team2Score + " points.\n");
}
}
public void play() throws InterruptedException {
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(this);
threads[i].start();
}
for (int quarter = 0; quarter < numQuarters; quarter++) {
System.out.println("Quarter " + (quarter + 1) + " started!");
currentQuarter = quarter;
for (int i = 0; i < numMaxPlayers; i++) {
ThreadLocalRandom random = ThreadLocalRandom.current();
boolean team1Possession = random.nextBoolean();
int points = random.nextInt(1, 3);
if (team1Possession) {
team1Score += points;
} else {
team2Score += points;
}
System.out.println("Player " + (i + 1) +
" from " + (team1Possession ? team1 : team2) +
" scored " + points + " points.\n" +
team1 + " has " + team1Score + " points.\n" +
team2 + " has " + team2Score + " points.\n");
}
synchronized (this) {
currentQuarter++;
notifyAll();
}
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("Game over!\n" +
team1 + " scored " + team1Score + " points.\n" +
team2 + " scored " + team2Score + " points.\n");
}
public static void main(String[] args) throws InterruptedException {
BasketballGame game = new BasketballGame("Lakers", "Warriors", 5, 4, 2);
game.play();
}
}
```
这个程序会创建 `numThreads` 个线程,每个线程运行一个 `BasketballGame` 实例。然后,在每个季节开始时,每个球员从两个队伍中随机选择一个,然后根据一定的概率进行得分。每个线程等待所有线程完成当前季度的比赛,然后输出比分。最后清空比分并开始下一个季度在新的独立线程中进行比赛,比赛运行完毕时结束。