java利用线程池实现石头剪刀布
时间: 2024-12-04 22:08:34 浏览: 7
在Java中,我们可以使用`java.util.concurrent`包下的`ExecutorService`和`ThreadPoolExecutor`来实现石头、剪刀、布的游戏并发场景。这里以固定大小线程池为例:
首先,创建一个`ThreadFactory`用于生成新的游戏参与者线程,然后创建`ThreadPoolExecutor`:
```java
import java.util.concurrent.*;
public class RPSGame {
private final ExecutorService threadPool = Executors.newFixedThreadPool(3, new NamedThreadFactory("Player"));
public void playRockPaperScissors(int playerCount) {
for (int i = 0; i < playerCount; i++) {
final int playerId = i;
threadPool.execute(() -> {
// 模拟玩家选择并发送结果
Random random = new Random();
String choice = "石头" + (random.nextInt(2) == 0 ? "" : "剪刀" + (random.nextInt(2) == 0 ? "" : "布"));
System.out.println("Player " + playerId + " chose " + choice);
});
}
// 等待所有任务完成
threadPool.shutdown();
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class NamedThreadFactory implements ThreadFactory {
private AtomicInteger counter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Player-" + counter.getAndIncrement());
return thread.setDaemon(true); // 设置守护线程
}
}
}
```
在这个例子中,`playRockPaperScissors`方法接受玩家的数量作为参数,然后为每个玩家创建一个新的线程,模拟他们的选择。线程池会管理这些线程的生命周期,并在游戏结束后自动关闭。
阅读全文