This lesson is about how to implement a runnable to run the Runnable.run () method on a separate thread. Runnable objects perform special operations sometimes called tasks.
Thread and runnable are basic classes that depend on themselves and have limited capacity. As a substitute, Android has a powerful base class, like Handlerthread,asynctask,intentservice. Thread and runnable are also basic classes of threadpoolexecutor. This class can automate the management of threads and task queues, and can even execute multithreading in parallel.
Defines a class that implements the Runnable interface
Copy Code code as follows:
public class Photodecoderunnable implements Runnable {
...
@Override
public void Run () {
/*
* Code you want to run on the thread goes
*/
...
}
...
}
Implementing the Run () method
The Runnable.run () method contains the code to execute. Usually, anything can be put in runnable. Remember that runnable does not run on the UI, so you cannot modify the UI object properties directly. Communicating with the UI, reference communicate with the UI Thread
At the start of the run () method, call Android.os.Process.setThreadPriority (Android.os.Process.THREAD_PRIORITY_BACKGROUND), set the weight of the thread, Android.os.Process.THREAD_PRIORITY_BACKGROUND is lower than the default weight, so resources are assigned priority to other threads (UI threads)
You should save the reference to the thread object by calling Thread.CurrentThread ()
Copy Code code as follows:
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 the instance
* Can interrupt the Thread.
*/
Mphototask.setimagedecodethread (Thread.CurrentThread ());
...
}
...
}