4

Looking for resources that teach multithreading in Android and list best practices. I want to do some image processing on the preview frame of the camera (already have this part set up) but want to parallelize the processing. Results from the async processes should come back to the main thread and update the UI.

I'm confused about how the following classes work together:

  • Thread

  • HandlerThread

  • Handler

  • Looper

Here's what I understand so far:

  • Threads can be used in different ways

    • A class that implements the Runnable interface
    • Using the Thread constructor and passing it an instance of Runnable, new Thread(new CustomRunnable())
    • Subclassing Thread and overriding run
  • Handlers are linked to a Looper on the thread where the Handler is instantiated. A looper contains a Message Queue which contain the results of the Threads. The messages are consumed by the calling thread's looper.

  • You are allowed to create your own Looper - why would you want to do this?

Some questions:

  • If a phone has 4 cores, and one thread is the UI thread can I run only 3 other processes in parallel ?

  • If I spawn threads at a high rate, say 30 times a second, is there such a thing as "running out of threads" ? Does Android handle the queueing of multiple threads? I'm imagining Android as a starter of a race with a checkered flag, the cars being the Runnables queued up to race, and the starter only lets 4 Runnables go at a time. Not sure if this is a correct assumption.

  • Do Android devices utilize virtual cores? How do I know how many virtual cores a device has, and how do I control them? Are there different ways to implement virtual cores, and is thread switching one of them?

Thanks for any guidance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.