This lesson talks about how to implement a Runnable and run the() method on an independent thread. The Runnable object performs special operations is sometimes called a task.
Thread and Runnable are both basic classes, relying on themselves and their abilities are limited. As an alternative, Android has powerful basic classes like HandlerThread, AsyncTask, IntentService. Thread and Runnable are also basic classes of ThreadPoolExecutor. This class can automatically manage threads and task queues, and can even execute multithreads in parallel.
Define a class that implements the Runnable interface
public class PhotoDecodeRunnable implements Runnable {
...
@Override
public void run() {
/*
* Code you want to run on the thread goes here
*/
...
}
...
}
Implement the run() method
The () method contains the code to be executed. Usually, anything can be put in the Runnable. Remember, Runnable will not run in the UI, so you cannot directly modify UI object properties. Communication with the UI Thread
At the beginning of the run() method, call (.THREAD_PRIORITY_BACKGROUND); set the weight of the thread. .THREAD_PRIORITY_BACKGROUND is less important than the default weight, so resources will be allocated to other threads (UI threads)
You should save a reference to the thread object by calling ()
class PhotoDecodeRunnable implements Runnable {
...
/*
* Defines the code to run for this task.
*/
@Override
public void run() {
// Moves the current Thread into the background
(.THREAD_PRIORITY_BACKGROUND);
...
/*
* Stores the current Thread in the PhotoTask instance,
* so that the instance
* can interrupt the Thread.
*/
(());
...
}
...
}