How to thread in Android?
I'm working on my first game, and it works fine, but clearly needs some optimizing. Initially, I had everything running on one thread (I used the LunarLander API to get started on gaming). Since then, I've added 2 new threads to the game. It still works just fine, but I see no improvement. I must be doing something wrong..
This is the basic setup:
class GameView extends SurfaceView implements SurfaceHolder.Callback {
private Mover mover;
private Collider collider;
private GameThread thread;
class Mover extends Thread{
//methods
}
class Collider 开发者_如何学编程extends Thread{
//methods
}
class GameThread extends Thread{
//methods
}
public GameView(Context context, AttributeSet attrs) {
mover = new Mover();
collider = new Collider();
thread = new GameThread();
thread.start();
}
}
Then, in the GameThread class I call methods on other threads when needed:
collider.checkCollision();
Is this the proper way to reduce load on the main thread?
Well, until they bring out dual-core phones, multiple threads isn't going to buy you anything in terms of performance improvements.
Multi threading can help when you're doing I/O intensive stuff on the additional threads (because they'll spend most of their time blocked on I/O, allowing your main thread to continue processing). But when you've got CPU-heavy stuff like collision-detection happening then you're just going to have those two thread fighting for the one CPU core.
Aside from what others have already pointed out, I would also like to mention a couple of other concepts that should be kept in mind when you're multithreading in general:
- Don't extend the Thread class- give it a Runnable! (from Jon Skeet himself)
- Take advantage of the ExecutorService when staring threads. (here is why)
You will probably find the most benefit from multithreading if you have some combination of the following (just off the top of my head):
- You have more than one core!
- You have tasks that can run independently of each other.
- You need to keep some portion of your app responsive (i.e. GUI), while another portion does some work (this is one of those exception cases where you may do multithreading on a single core).
- You can easily determine the main points of contention and you can "eliminate" them in a reasonable way (lock-free, wait-free, or with some synchronization).
精彩评论