Count the classes in frequently-used concurrent libraries in the Android open-source project

Source: Internet
Author: User

Count the classes in frequently-used concurrent libraries in the Android open-source project
This blog aims to help you sort out some of the classes that we like to use in the open-source code analyzed earlier, which is of great benefit to us to truly understand these projects, if we encounter similar problems in the future, we can imitate them and write similar code. 1. ExecutorService is actually an interface 1 public interface ExecutorService extends Executor {we can see which frequently used classes implement this interface, but there are actually three.

 1  /** 2      * Creates a thread pool that reuses a fixed number of threads 3      * operating off a shared unbounded queue.  At any point, at most 4      * {@code nThreads} threads will be active processing tasks. 5      * If additional tasks are submitted when all threads are active, 6      * they will wait in the queue until a thread is available. 7      * If any thread terminates due to a failure during execution 8      * prior to shutdown, a new one will take its place if needed to 9      * execute subsequent tasks.  The threads in the pool will exist10      * until it is explicitly {@link ExecutorService#shutdown shutdown}.11      *12      * @param nThreads the number of threads in the pool13      * @return the newly created thread pool14      * @throws IllegalArgumentException if {@code nThreads <= 0}15      */16     public static ExecutorService newFixedThreadPool(int nThreads) {17         return new ThreadPoolExecutor(nThreads, nThreads,18                                       0L, TimeUnit.MILLISECONDS,19                                       new LinkedBlockingQueue<Runnable>());20     }

 

This thread pool is a thread pool with a fixed number of threads and a shared unbounded queue to run these threads.
 1 /** 2      * Creates a thread pool that creates new threads as needed, but 3      * will reuse previously constructed threads when they are 4      * available.  These pools will typically improve the performance 5      * of programs that execute many short-lived asynchronous tasks. 6      * Calls to {@code execute} will reuse previously constructed 7      * threads if available. If no existing thread is available, a new 8      * thread will be created and added to the pool. Threads that have 9      * not been used for sixty seconds are terminated and removed from10      * the cache. Thus, a pool that remains idle for long enough will11      * not consume any resources. Note that pools with similar12      * properties but different details (for example, timeout parameters)13      * may be created using {@link ThreadPoolExecutor} constructors.14      *15      * @return the newly created thread pool16      */17     public static ExecutorService newCachedThreadPool() {18         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,19                                       60L, TimeUnit.SECONDS,20                                       new SynchronousQueue<Runnable>());21     } 

 

This thread pool is used to create these threads as needed, but previously constructed threads can be reused when necessary, so this is useful in many open-source android projects, this thread pool can greatly improve program performance for executing many short-term asynchronous tasks.
 1 /** 2      * Creates an Executor that uses a single worker thread operating 3      * off an unbounded queue. (Note however that if this single 4      * thread terminates due to a failure during execution prior to 5      * shutdown, a new one will take its place if needed to execute 6      * subsequent tasks.)  Tasks are guaranteed to execute 7      * sequentially, and no more than one task will be active at any 8      * given time. Unlike the otherwise equivalent 9      * {@code newFixedThreadPool(1)} the returned executor is10      * guaranteed not to be reconfigurable to use additional threads.11      *12      * @return the newly created single-threaded Executor13      */14     public static ExecutorService newSingleThreadExecutor() {15         return new FinalizableDelegatedExecutorService16             (new ThreadPoolExecutor(1, 1,17                                     0L, TimeUnit.MILLISECONDS,18                                     new LinkedBlockingQueue<Runnable>()));19     } 

 

This thread pool is quite special. It only has one worker thread working. Let's look at the first program:
1 public class Test1 {2 3 public static void main (String [] args) {4 ExecutorService exectrorService = Executors. newFixedThreadPool (10); 5 // execute the Asynchronous Method to execute this runnable, but this method cannot obtain the returned value after running 6 exectrorService.exe cute (new Runnable () {7 @ Override 8 public void run () {9 // TODO Auto-generated method stub10 int I = 0; 11 while (true) {12 try {13 Thread. sleep (2000); 14} catch (InterruptedException e) {15 // TODO Auto-generated catch block16 e. printStackTrace (); 17} 18 System. out. println (I); 19 I ++; 20} 21} 22 23}); 24 25 exectrorService.exe cute (new Runnable () {26 @ Override27 public void run () {28 // TODO Auto-generated method stub29 int I = 100; 30 while (true) {31 try {32 Thread. sleep (2000); 33} catch (InterruptedException e) {34 // TODO Auto-generated catch block35 e. printStackTrace (); 36} 37 System. out. println (I); 38 I ++; 39} 40} 41 42 });

 

There is nothing to say, just to demonstrate this method, continue to look at it:
1 public class Test1 {2 3 public static void main (String [] args) {4 ExecutorService exectrorService = Executors. newFixedThreadPool (10); 5 Future future = exectrorService. submit (new Runnable () {6 7 @ Override 8 public void run () {9 System. out. println ("thread start"); 10 // TODO Auto-generated method stub11 try {12 Thread. sleep (13000); 13} catch (InterruptedException e) {14 // TODO Auto-generated catch block15 e. printStackTrace (); 16} 17 System. out. println ("task done"); 18} 19}); 20 System. out. println ("ready to print status"); 21 try {22 // null is returned only after the execution is completed. If the thread has not completed the execution, the 23 System is blocked. out. println ("future. get = "+ future. get (); 24} catch (InterruptedException e) {25 // TODO Auto-generated catch block26 e. printStackTrace (); 27} catch (ExecutionException e) {28 // TODO Auto-generated catch block29 e. printStackTrace (); 30} 31 System. out. println ("finish ready ");

 


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.