Create a multithreaded manager instance in Android _android

Source: Internet
Author: User

If you're going to perform a task over and over again with a different dataset (with different parameters), but only one execution at a time (the task is single-threaded), Intentservice meets your needs. When you need to automate tasks when a resource is available, or allow multitasking to execute at the same time, you need a thread manager to manage your threads. Threadpoolexecutor maintains a queue that takes tasks from the queue and executes when its thread pool is empty. To run a task, all you have to do is add it to the queue.

The thread pool can run multiple instances of a task in parallel, so you want to save code thread safety. Variables that can be accessed by multithreading require synchronized blocks. For more information, see Processes and Threads (http://developer.android.com/guide/components/processes-and-threads.html)

To define a thread pool class

Instance Threadpoolexecutor in its own class. In the class, the following actions are:

to use a static variable for a thread pool

You may only need a single example thread pool in the app for unified control of limiting CPU or network resources. If you have different runnable types, you may want each type to have its own thread pool, but these can be placed in a single instance. For example, you can declare it as a global variable:

Copy Code code as follows:

public class Photomanager {
...
static {
...
Creates a single static instance of Photomanager
Sinstance = new Photomanager ();
}
...

Use private construction method

By declaring the construction method private, you can ensure a single example, which means that you do not need to encapsulate class access in a synchronized code block.

Copy Code code as follows:

public class Photomanager {
...
/**
* Build work queues and thread pools to download and decode pictures, because the construction method is marked private,
* Inaccessible to other classes (even classes under the same package)
*/
Private Photomanager () {
...
}

Call methods in the thread pool class to start the task

Thread pool class to define a method that adds a task to a thread pool queue, such as:

Copy Code code as follows:

public class Photomanager {
...
Get pictures for Photoview call
static public Phototask Startdownload (
Photoview ImageView,
Boolean Cacheflag) {
...
Add a task to the thread pool
Sinstance.
Mdownloadthreadpool.
Execute (downloadtask.gethttpdownloadrunnable ());
...
}

Instantiates the handler of a UI thread.

Handler is used to communicate with the UI thread, and most UI controls are only allowed to be modified in the UI thread.

Copy Code code as follows:

Private Photomanager () {
...
Defines a Handler object that ' s attached to the UI thread
Mhandler = new Handler (Looper.getmainlooper ()) {
/*
* Handlemessage () defines the operations to perform
* The Handler receives a new message to process.
*/
@Override
public void Handlemessage (message inputmessage) {
...
}
...
}
}

To determine the thread pool parameters

Once you have all the class structure, you can begin to define the thread pool. To instantiate a thread pool object, you need the following value:
Initial pool size, maximum pool size.
The number of threads in the thread pool depends primarily on the number of CPU cores in the device. Can be obtained from the system environment.

Copy Code code as follows:

public class Photomanager {
...
/*
* Gets the number of available cores
* (not always the same as the maximum number of cores)
*/
private static int number_of_cores =
Runtime.getruntime (). Availableprocessors ();
}

This number may not reflect the number of physical CPU cores for the device, and some device CPUs will automatically disable some of the cores based on the system load, and for those devices, availableprocessors () returns the current number of active cores.

Maintain active time and time units

the time that a process remains idle before it is closed (the process can be reused). Time unit in Timeunit.

Task queues

The Threadpoolexecutor queue saves the Runnable object. The thread pool manager takes a runnable object out of a FIFO queue and attaches it to the thread while executing the code. The queue implements the Blockingqueue interface, which is provided when the thread pool is created. You can choose from existing implementations to suit your needs, see Threadpoolexecutor. The following are examples of using linkedblockingqueue:

Copy Code code as follows:

public class Photomanager {
...
Private Photomanager () {
...
A Queue of Runnables
Private final blockingqueue<runnable> Mdecodeworkqueue;
...
Instantiates the queue of runnables as a linkedblockingqueue
Mdecodeworkqueue = new linkedblockingqueue<runnable> ();
...
}
...
}

Creating a thread pool

Call the Threadpoolexecutor () method to initialize the thread pool. It creates an administrative thread. Because the initial size of the thread pool is the same as the maximum pool size, Threadpoolexecutor creates all the thread objects when it is initialized, such as:

Copy Code code as follows:
Private Photomanager () {
...
Sets The amount of time a idle thread waits before terminating
private static final int keep_alive_time = 1;
Sets to Seconds
private static final Timeunit keep_alive_time_unit = timeunit.seconds;
Creates a thread pool manager
Mdecodethreadpool = new Threadpoolexecutor (
Number_of_cores,//Initial pool Size
Number_of_cores,//Max pool Size
Keep_alive_time,
Keep_alive_time_unit,
Mdecodeworkqueue);
}

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.