A simple example of implementing the Runnable interface in Android

  • 2020-06-01 11:00:57
  • OfStack

This lesson describes how to implement an Runnable by running the Runnable.run () method on a separate thread.Runnable objects perform special operations sometimes called tasks.
Thread and Runnable are both basic classes, on their own, with limited capabilities. Instead, Android has powerful base classes like HandlerThread, AsyncTask, IntentService. Thread and Runnable are also base classes for ThreadPoolExecutor. This class can automatically manage threads and task queues, and can even execute multiple threads 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 Runnable.run () method contains the code to execute. In general, you can put anything in Runnable. Remember, Runnable does not run on UI, so you cannot directly modify the UI object properties. Communicate with UI and refer to Communicate with the UI Thread
In run start () method, called android. os. Process. setThreadPriority (android. os. Process. THREAD_PRIORITY_BACKGROUND); Set the weight of the thread, android. os. Process. THREAD_PRIORITY_BACKGROUND is more important than the default power is low, so that resources will be priority assigned to other threads (UI thread)
You should save the reference to the thread object by calling Thread.currentThread ()


class PhotoDecodeRunnable implements Runnable {
...
    /*
     * Defines the code to run for this task.
     */
    @Override
    public void run() {
        // Moves the current Thread into the background
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
        ...
        /*
         * Stores the current Thread in the PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}


Related articles: