Junior
How to execute code in a parallel thread different from the main one?
sobes.tech AI
Answer from AI
Using one of the following mechanisms:
-
Kotlin Coroutines: Lightweight, asynchronous framework for cooperative multitasking.
GlobalScope.launch { // Code running in a parallel thread } -
Java
Executor/ExecutorService: Thread pool management.ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { // Code running in a parallel thread } }); -
Threadclass: Creating and managing a separate thread.new Thread(new Runnable() { @Override public void run() { // Code running in a parallel thread } }).start(); -
AsyncTaskclass (less preferred in modern applications): Simplified mechanism for executing operations in the background and updating the UI.new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { // Code running in a parallel thread return null; } }.execute();