So, I’m in doubt to which way is the most optimal in the situation given below:
I have a simulation of vehicles moving along roads on a map. Moving them is no problem and they obey traffic lights etc. However my question is, what’s the most efficient way of moving the vehicles. Right now I have a thread per road so one thread moves vehicles along the road going south to north, another one for the road going from west to east etc. But it’s not very optimal and very slow. Also, I’m finding it hard to allow the thread to keep track of the distances between the cars so they can slow down and not run past each other.
Do I need to have a thread pool using the Executor class in the java.util.concurrent package and then have one thread per vehicle and then free the thread once the vehicle leaves the simulation? Or will this too make it slow?
So in conclusion if I did not make it clear above, I’m attempting to find an optimal way of keeping track of vehicles currently in the simulation(map). I have tried to have one thread per road letting vehicles through but it’s not a good solution as I eventually need the vehicles to have their own sort of logic.
I would have one thread for the whole simulation. The locking overhead (CPU and coding overhead) is likely to be greater than the benefit of having multiple threads.
I would have a method to call on each object like
move()and is called for all objects repeatedly in the one thread. Each car or object knows how it should move.