2D Graphics using Multi-threading

• 2 min read •

A - Introduction Multi-threading

To a game developer, Multi-threading is a must-know term.

Multi-threading is used when your application needs to do a lot tasks parallely. By this way, all the tasks will run parallely and don’t have to wait for the others finished.

B - 2D Graphics using Multi-threadingĀ Demo description

The application will draw a moving green ball on the screen.

When user tap on the ball when it’s moving, It’ll stop andĀ vice versa.

In this demo, there’re 2 thread run parallely:

  • One will calculate the position and draw to canvas
  • One will detect the tap event and handle it

C - Demo implementation

Firstly, create GameView class:
  • Extends from Ā SurfaceView class
  • Implements SurfaceHolder.CallbackĀ method
  • Override all the methods surfaceChanged(), surfaceCreated(), surfaceDestroyed()
  • Override Ā onTouchEvent() method to "catch" the event then call the doTouch() method of GameThread to handle it.

As you can see, GameView is the screen where the ā€œgreen ballā€ moving. GameView will also catch all the user interactions event.

Hence, we cannot let the GameView take responsibility for calculating and drawing the green ball —> We need to create a new Thread to handle it!

Ā 

Create Ā GameThread class:

  • Extends Thread.
  • private SurfaceHolder holder : this variable reference to GameView, used to display the green ball.
  • run(): used to draw the green ball on the GameView.
  • doTouch(): do some logical calculation when user touch the ball.

Finally, in MainActivity, call Ā setContentView(new GameView(this, null))

Enjoy the result:

D - Download Source Code

http://www.mediafire.com/download.php?8nca1ra07nwp554
Iced Tea Labs

A technical blog managed by a geek who loves climbing

GitHub Twitter RSS

Ā© 2026 Trinh Le. All rights reserved.