0

How can I create a for loop which creates multiple threads which can be identifiable. The threads are Players in a game and need to communicate with each other. I need to be able to access each player's getters and setters.

Basically, each Player has a name attribute and needs to be identifiable. If i do this, I don't see how they are identifiable from one another...

for (int i = 0; i < numberOfPlayers; i++)
    {
        Thread t = new Thread(new Player("Player" + (i + 1), (i + 1), (i + 2)));
    }
1
  • if you need to start the thread just after declaring t call the start() method as t.start(); and this tutorial would help you, or these examples Commented Jul 11, 2013 at 19:48

2 Answers 2

2

One option is to create a Map of players, and pass this Map to each Player so that they can communicate with each other directly (or make the map static so that it's visible to all Player objects, or whatever)

Map<String, Player> players = new HashMap<>();
for(int i = 0; i < numberOfPlayers; i++) {
    players.put("Player" + (i + 1), new Player("Player" (i + 1), (i + 1), (i + 2), players));
}
for(Player player : map.values()) {
    new Thread(player).start();
}

Another option is to create a class that acts as a message bus that has access to all of the players' setters - if a player wants to send a message to another player then it sends the message to the message bus, which then takes care of calling the appropriate setter method(s)

Sign up to request clarification or add additional context in comments.

1 Comment

You can then make the message bus threaded so that the player doesn't have to block to communicate with the other players.
1

If you know the numberOfPlayers then create an array of Thread, and populate it inside the loop:

Thread[] players = new Thread[numberOfPlayers];

for (int i = 0; i < numberOfPlayers; i++) {
    players[i] = new Thread(new Player("Player" + (i + 1), (i + 1), (i + 2)));
    // You can start the thread here only
}

But if you don't know the numberOfPlayers in advance, while creating the array, you can create an ArrayList<Thread> and add each new thread to it:

List<Thread> players = new ArrayList<Thread>();

for (int i = 0; i < numberOfPlayers; i++) {
    players.add(new Thread(new Player("Player" + (i + 1), (i + 1), (i + 2))));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.