Use wait and notify to ensure that only one of your threads is modifying the object at a time. You'll need a class to hold your ArrayList:
class GameObjectManager {
private ArrayList<GameObject> objects;
private Boolean rendering = false;
public GameObjectManager(){
//Initialize objects
}
public synchronized void update() {
if (rendering)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
// update objects...
rendering = true;
notify();
}
public synchronized void render() {
if (!rendering)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
// render objects...
rendering = false;
notify();
}
}
The Update thread might look something like this:
class UpdateThread implements Runnable {
private GameObjectManager manager;
public UpdateThread(GameObjectManager m) {
this.manager = m;
new Thread(this, "Update").start();
}
public void run() {
while (true) {
m.update();
}
}
}
The Render thread would follow suit:
class RenderThread implements Runnable {
private GameObjectManager manager;
public RenderThread(GameObjectManager m) {
this.manager = m;
new Thread(this, "Render").start();
}
public void run() {
while (true) {
m.render();
}
}
}
Now the main function that controls it all would do something resembling this:
public static void main(String args[]) {
GameObjectManager manager = new GameObjectManager();
new UpdateThread(manager);
new RenderThread(manager);
System.out.println("The game is running now...");
}
So here's what happens:
1. The main function creates two threads, the update and render threads.
2. Both threads try to do their task, but the GameObjectManager
forces the render thread to wait()
until the update thread has called notify()
.
3. The update thread finishes updating, notifies the render thread, and then waits.
4. The render thread finishes rendering, notifies the update thread, and then waits.
And so on.
Collection
thread safe? One way to achieve this is using the synchronizedCollection method. \$\endgroup\$