java - Making multiple threads in a loop -


how can create loop creates multiple threads can identifiable. threads players in game , need communicate each other. need able access each player's getters , setters.

basically, each player has name attribute , needs identifiable. if this, don't see how identifiable 1 another...

for (int = 0; < numberofplayers; i++)     {         thread t = new thread(new player("player" + (i + 1), (i + 1), (i + 2)));     } 

one option create map of players, , pass map each player can communicate each other directly (or make map static it's visible player objects, or whatever)

map<string, player> players = new hashmap<>(); for(int = 0; < 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 create class acts message bus has access of players' setters - if player wants send message player sends message message bus, takes care of calling appropriate setter method(s)


Comments