Reputation: 1057
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)));
}
Upvotes: 0
Views: 81
Reputation: 18148
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)
Upvotes: 2
Reputation: 213243
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))));
}
Upvotes: 1