Thread in Android
Thread
A thread is the unit of execution within a process.
Java provides two ways to create a thread programmatically.
Way 1) Extending the java.lang.Thread class.
new ExampleThread().start();
//Step 1 - Extend the Thread base class
class ExampleThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Way 2) Implementing the java.lang.Runnable interface.
new Thread(new ExampleRunnable()).start();
//Step 2- Implement Runnable class
class ExampleRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
start() method of Thread class is used to start a newly created thread.
Background Thread (Worker Thread) VS Main Thread in Android
Background (Worker) Thread:
In Android "background" and "worker" threads are the same
Ref: https://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads
Main (UI) Thread:
Main Thread. When a Java program starts up, one thread begins running immediately. that is responsible for handling the UI events like Draw, Listen and receive the UI events.
It will be the thread that owns and manages UI. And then you start one or more worker threads that do specific tasks.
Thread vs AsynTask
Thread can be triggered from any thread, Main(UI) thread or background (worker) thread
AsyncTask must be triggered from main thread.
Comments
Post a Comment