damian
damian

Reputation: 2011

Android, Multiple Threads, Synchronization

I'm developing a relatively small 2D game for Android right now. To process the collision detections as efficient as possible, I've created multiple threads working on the calculations:

Thread #1: Main handling of the frames, limiting them to X per second, handling the Bitmaps (rotate, draw...) Thread #2: Calculate some collisions Thread #3: Calculate other collisions

What I need is some sort of synchronization, but I am unsure of what's the best way to achieve this. I thought of something like this:

Thread #1:

public class Thread1 imlements Runnable {
    public static ArrayList<Boolean> ResponseList = new ArrayList<Boolean>();
    static {
        ResponseList.add(0, false); // index 0 -> thread 1
        ResponseList.add(1, false); // index 1 -> thread 2
    }
    public void run() {
        boolean notFinished;
        while(!isInterrupted() && isRunning) {
            notFinished = true;
            // do thread-business, canvas stuff, etc, draw



            while(notFinished) {
                notFinished = false;
                for(boolean cur: ResponseList) {
                    if(!cur) notFinished = true;
                }
                // maybe sleep 10ms or something
            }
        }
    }
}   

And in the other calculation threads something like:

public class CalcThread implements Runnable {
    private static final INDEX = 0;

    public void run()  {
        while(isRunning) {
            ResponseList.set(INDEX, false);
            executeCalculations();
            ResponseList.set(INDEX, true);
        }
    }
}

Or would it be faster (as this is what I'm concerned about) to use a Looper/Handler combination? Just read about this, but I'm not sure yet how to implement this. Would look deeper into this is this would be the more efficient method.

Upvotes: 0

Views: 1779

Answers (1)

msh
msh

Reputation: 2770

I don't know if it is going to be faster, but it will be more reliable for sure. For example, you are using ArrayList from multiple threads without serialization and ArrayList is not thread-safe

Handler is just one of the available mechanisms, I would recommend you to study java.util.concurrent - there is no point in reinventing the wheel, many synchronization primitives are already available. Perhaps Future would work for you

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

Upvotes: 0

Related Questions