Junior — Middle
How to implement a thread pool for executing tasks in your application?
sobes.tech AI
Answer from AI
To implement a thread pool in an Android application, you can use the ThreadPoolExecutor class from Java or Kotlin.
Example in Kotlin using Executors.newFixedThreadPool:
import java.util.concurrent.Executors
// Create a pool of 4 threads
val threadPool = Executors.newFixedThreadPool(4)
// Submit tasks for execution
threadPool.execute {
// Task 1 code
println("Task 1 is running in thread ${Thread.currentThread().name}")
}
threadPool.execute {
// Task 2 code
println("Task 2 is running in thread ${Thread.currentThread().name}")
}
// After completing the work, properly shut down the pool
threadPool.shutdown()
If you are using Kotlin Coroutines, you can use Dispatchers.IO or create your own thread pool via newFixedThreadPoolContext.
A thread pool limits the number of threads running simultaneously, which helps efficiently utilize resources and avoid creating too many threads.