用Java的线程池功能实现石头剪刀布
时间: 2024-02-28 22:49:23 浏览: 86
以下是使用Java线程池功能实现石头剪刀布游戏的示例代码:
```java
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RockPaperScissorsGame {
private static final int NUM_PLAYERS = 2;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NUM_PLAYERS);
for (int i = 0; i < NUM_PLAYERS; i++) {
executor.execute(new Player(i));
}
executor.shutdown();
}
static class Player implements Runnable {
private static final String[] CHOICES = {"石头", "剪刀", "布"};
private int playerId;
public Player(int playerId) {
this.playerId = playerId;
}
@Override
public void run() {
Random random = new Random();
int choiceIndex = random.nextInt(CHOICES.length);
String choice = CHOICES[choiceIndex];
System.out.println("玩家 " + playerId + " 出的是:" + choice);
}
}
}
```
这个示例中,我们使用了Java的线程池功能来创建一个固定大小的线程池。然后,我们创建了两个玩家线程,每个玩家线程都会随机选择石头、剪刀或布,并输出选择结果。
阅读全文