I am working on a game using the thread-per-client model. The game operates so that every half a second all of the players need to be updated. The updates all have to happen within the half a second interval, so they need to all be executed at the same time. My idea is to have a class that keeps track of when the "global update" needs to happen and then when the time comes, go through all of the players and tell it to update:
for(Player p : currentPlayers) {
p.update();
}
The problem is that since every player has their own thread, I want the player to take advantage of that fact since it is already there. If I go through the updates from a different class, then there is one thread executing what a couple hundred threads could be doing individually. How can I design it so that if a thread calls method 'update()' in class Player, a different thread than the one that called it executes it, or perhaps a different approach that can achieve the same goal?
If you need any clarification, please ask! Thanks a lot!
UPDATE: What do you guys think of this (I can't figure out how to format long amounts of code in posts!):
UPDATE 2: Just realized I would need to know when all of the players finish updating to reset the last time...
public class PseudoExample implements Runnable { // Assume 'players' is full of active players. private Player[] players = new Player[100]; private long lastUpdate = System.currentTimeMillis(); public void run() { while (true) { if (System.currentTimeMillis() - lastUpdate >= 500) { for (Player p : players) { p.update = true; } } try { Thread.sleep(10); } catch (InterruptedException e) { } } } private class Player implements Runnable { private boolean update = false; public void run() { while (true) { if (update) { // Do updating here ... } try { Thread.sleep(10); } catch (InterruptedException e) { } } } } }