Android Thread (i)

Source: Internet
Author: User

1. New Thread

New Thread (New Runnable () {        @Override public      void Run () {          //TODO auto-generated method stub      }  }). Start ();  


This is the most basic way to open threads (Implementation of the Runnable interface), we are beginners in Android or early development of Android developers are using this method to open threads, in addition there are two ways to open threads: Inherit the thread class rewrite the run () method and implement the callable interface, overriding Call () method, which is not introduced here.

But the above three ways to turn on threading have the following drawbacks when we write Android apps:

1. But we all know that the Java threading mechanism is preemptive, scheduling the opportunity to break the thread, switch the context to the other threads, so that each thread is given a time slice, so that each thread will allocate a reasonable time to drive its task, Java provides a way to change the thread priority, But this can be very difficult to maintain, and trying to manipulate the thread priority is usually wrong.

2. Each time the thread is created threads, the destruction of thread performance will be poor

3. And there are three ways to open threads that lack more functionality, such as timed execution, periodic execution, and thread interruption.

We can do this when we're writing programs, but it's not recommended if you have a lot of thread-opening operations.

2. Java thread Pool
Java provides four thread pools through executors, namely:
Cachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable. Threads are terminated after the thread has been idle for 60 seconds.
Fixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Scheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Singlethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

The executors class is used to manage thread objects, simplifying the concurrency process, and we can see the creation process of Fixedthreadpool:

public static Executorservice newfixedthreadpool (int nthreads) {  return new Threadpoolexecutor (Nthreads, Nthreads,                                    0L, Timeunit.milliseconds,                                    new linkedblockingqueue<runnable> ());  }  

Obviously these four thread pool methods are returning the Threadpoolexecutor that implements the Executorservice interface. Of course we can also directly use Threadpoolexecutor to customize a more flexible thread pool.

Let's take a look at the construction parameters of Threadpoolexecutor:

Public threadpoolexecutor (int corepoolsize,                           int maximumpoolsize,                          long KeepAliveTime,                          timeunit Unit,                           blockingqueue<runnable> WorkQueue,                          Threadfactory Threadfactory,                            

When the pool size is less than corepoolsize to create a new thread, and processing the request, when the pool size equals corepoolsize, put the request into the workqueue, the free thread in the pool to take the task from the Workqueue and processing, When Workqueue does not fit into the new task, the new thread sinks into the pool and processes the request, and if the pool size is propped up to maximumpoolsize, use Rejectedexecutionhandler to do the reject processing. Additionally, when the number of threads in the pool is greater than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.


Next we look at Cachedthreadpool:

public static Executorservice Newcachedthreadpool () {      return new Threadpoolexecutor (0, Integer.max_value,                                   60L , Timeunit.seconds,                                    new synchronousqueue<runnable> ());  }  

Cachedthreadpool creates the same thread as required when the program executes, and then stops creating a new thread when it recycles the old thread, so it is the preferred choice for executor, only if this way causes the problem. Or do not meet the business needs of the other three kinds of executor provided thread pool

Singlethreadexecutor is a fixedthreadpool with a thread number of 1, and if you submit multiple tasks to Singlethreadexecutor, the tasks are queued, Each task ends before the next task starts, and all tasks are in one thread and executed in the order in which they were submitted.

The thread pool is used for scenarios where the number of threads is relatively large, and if only 2 is turned on and 3 threads are using the thread pool, it is obviously a waste of resources

Android Thread (i)

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.