帮我写一个java多线程一个发牌线程和取牌线程的java语言程序
时间: 2024-12-23 22:20:06 浏览: 14
在Java中,你可以创建一个发牌线程(DeckShufflerThread)和一个取牌线程(CardPickerThread),这两个线程可以模拟一个简单的扑克游戏。下面是一个基本的示例,使用了`synchronized`关键字来处理并发安全:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
// 定义一副牌
class Deck {
private List<Card> cards = new ArrayList<>();
private static final int CARDS_COUNT = 52; // 一副扑克牌的数量
public void initializeDeck() {
for (int suit : Suit.values()) {
for (int rank : Rank.values()) {
cards.add(new Card(rank, suit));
}
}
}
synchronized void shuffle() {
Random random = new Random();
for (int i = cards.size() - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
Card temp = cards.get(i);
cards.set(i, cards.get(j));
cards.set(j, temp);
}
}
synchronized Card drawTopCard() {
if (cards.isEmpty()) {
throw new IllegalStateException("The deck is empty");
}
return cards.remove(0);
}
}
// 定义牌的花色和点数
enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES }
enum Rank { ACE, TWO, THREE, ..., KING }
// 记录每张牌的数据
class Card {
private final Rank rank;
private final Suit suit;
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
// ... getters and setters
}
// 发牌线程
class DeckShufflerThread extends Thread {
private final Deck deck;
public DeckShufflerThread(Deck deck) {
this.deck = deck;
}
@Override
public void run() {
while (!deck.cards.isEmpty()) {
deck.shuffle();
}
}
}
// 取牌线程
class CardPickerThread extends Thread {
private final Deck deck;
public CardPickerThread(Deck deck) {
this.deck = deck;
}
@Override
public void run() {
try {
while (true) {
System.out.println(Thread.currentThread().getName() + " picked a card: " + deck.drawTopCard());
}
} catch (IllegalStateException e) {
System.out.println("No more cards in the deck.");
}
}
}
public class PokerGame {
public static void main(String[] args) {
Deck deck = new Deck();
deck.initializeDeck();
DeckShufflerThread shuffler = new DeckShufflerThread(deck);
shuffler.start(); // 启动发牌线程
CardPickerThread picker = new CardPickerThread(deck);
picker.start(); // 同时启动取牌线程
}
}
```
在这个例子中,发牌线程负责打乱牌堆,而取牌线程会不断从牌堆顶部取出一张牌并打印出来。注意,`shuffle()` 和 `drawTopCard()` 被声明为`synchronized`,确保在同一时刻只有一个线程能访问它们,防止数据竞争。
阅读全文