Simple example of implementing Runnable interface in Android _android

Source: Internet
Author: User

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 ());
...
}
...
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.