How exactly to implement multiple threads in a game
Posted
by
xerwin
on Game Development
See other posts from Game Development
or by xerwin
Published on 2013-11-05T15:48:30Z
Indexed on
2013/11/05
16:14 UTC
Read the original article
Hit count: 259
java
|multithreading
So I recently started learning Java, and having a interest in playing games as well as developing them, naturally I want to create game in Java.
I have experience with games in C# and C++ but all of them were single-threaded simple games.
But now, I learned how easy it is to make threads in Java, I want to take things to the next level. I started thinking about how would I actually implement threading in a game. I read couple of articles that say the same thing "Usually you have thread for rendering, for updating game logic, for AI, ..." but I haven't (or didn't look hard enough) found example of implementation.
My idea how to make implementation is something like this (example for AI)
public class AIThread implements Runnable{
private List<AI> ai;
private Player player;
/*...*/
public void run() {
for (int i = 0; i < ai.size(); i++){
ai.get(i).update(player);
}
Thread.sleep(/* sleep until the next game "tick" */);
}
}
I think this could work. If I also had a rendering and updating thread list of AI in both those threads, since I need to draw the AI and I need to calculate the logic between player and AI(But that could be moved to AIThread, but as an example) . Coming from C++ I'm used to do thing elegantly and efficiently, and this seems like neither of those.
So what would be the correct way to handle this? Should I just keep multiple copies of resources in each thread or should I have the resources on one spot, declared with synchronized
keyword? I'm afraid that could cause deadlocks, but I'm not yet qualified enough to know when a code will produce deadlock.
© Game Development or respective owner