Middle
What methods of multithreading are available?
sobes.tech AI
Answer from AI
Thread: The basic class for creating a new thread. Requires manual management of its lifecycle.AsyncTask: Deprecated way to perform short operations in a background thread and update the UI. Tied to the lifecycle of Activity/Fragment, which can lead to memory leaks.HandlerThread: A specialized thread with a Looper, allowing message processing in the background.ExecutorService/ThreadPoolExecutor: Provide thread pools for efficient management and reuse of threads. Enable asynchronous task execution.Coroutines(Kotlin): Lightweight threads built on top of JVM threads. Offer a more convenient and readable way to write asynchronous code. Support structured concurrency.RxJava/RxKotlin: Libraries for reactive programming, allowing working with asynchronous data streams. Provide a rich set of operators for transforming and combining data.
Examples of using Coroutines:
import kotlinx.coroutines.*
fun fetchData() {
GlobalScope.launch(Dispatchers.IO) {
// Executes in a background thread (for I/O operations)
val data = apiService.getData()
withContext(Dispatchers.Main) {
// Executes on the main (UI) thread
updateUI(data)
}
}
}