Junior — Middle
How to implement multithreading in a program?
sobes.tech AI
Answer from AI
To implement multithreading in an Android application, several approaches can be used:
- Thread Class — create a new thread by overriding the
run()method:
new Thread(new Runnable() {
@Override
public void run() {
// code to execute in a separate thread
}
}).start();
-
Using Handler and Looper — for message exchange between threads.
-
AsyncTask (deprecated but still common) — simplifies executing background tasks with UI updates.
-
ExecutorService — a thread pool for managing multiple tasks.
-
Kotlin Coroutines — a modern and convenient way of asynchronous programming, allowing writing code similar to synchronous code.
Example of creating and starting a thread:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Long-running operation
}
});
thread.start();
It is important to remember that UI updates should only occur on the main thread (UI thread), so mechanisms like Handler, runOnUiThread(), or others are used to pass results from background threads.