Member-only story
Android Interview Question Answer: Thread, Coroutines Explained
Continue your Android interview preparation with Part 4 of our series! Covering advanced concepts, best practices, and real-world Android development interview questions. Read Part 4 here link on Activity and Fragment.
Thread
What is Thread? how to create and run it.
A Thread is a lightweight process that allows running background operations without blocking the main UI thread.
There are two ways you can create and run the thread
- Using the thread class
- Using runnable interface
To create a thread we need to extend the class from the thread class
- Using the thread class
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running...");
}
}
fun main(){
// Start the thread
MyThread thread = new MyThread();
thread.start();
}
2. Using Runnable interface
As the thread implements the Runnable interface and has a constructor that can allow us to pass the Runnable implementation we can use that to create the thread.
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable thread is running...");
}
}
// Start the thread
Thread thread = new Thread(new MyRunnable());
thread.start();