Android thread pool (1) -- Executors (thread pool) and FutureTask usage example, android Thread Pool

Source: Internet
Author: User

Android thread pool (1) -- Executors (thread pool) and FutureTask usage example, android Thread Pool
MainActivity is as follows:

Package cc. vv; import java. util. arrayList; import java. util. iterator; import java. util. concurrent. executor; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. futureTask; import android. OS. bundle; import android. app. activity;/*** Demo Description: * thread pool example ** main method for creating a thread pool: * newCachedThreadPool () * newFixedThreadPool (int I) * newScheduledThreadPool (int I) * SingleThreadExecutor () ** Demo content: * 1 Use of newFixedThreadPool (int I) and SingleThreadExecutor () * 2 Use of Thread Pool (Executors) and FutureTask ** references: * 1 http://blog.csdn.net/ns_code/article/details/17465497 * 2 http://blog.csdn.net/tounaobun/article/details/8586675 * 3 http://blog.csdn.net/linghu_java/article/details/17123057 * 4 http://blog.csdn.net/andycpp/article/details/8902655 * Thank you very much */p Ublic class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // testExecutors1 (); // testExecutors2 (); testExecutors3 ();} //////////////////////////////////////// /// // /// *** use of newFixedThreadPool * 1. Create a thread pool, there are 5 threads in the thread pool * 2 put 15 RunnableImpl objects into the thread for execution * you can see these 15 RunnableImpl Call **/private void testExecutors1 () {Executor executor = Executors in five threads. newFixedThreadPool (5); RunnableImpl1 runnableImpl1 = null; for (int I = 0; I <15; I ++) {runnableImpl1 = new datagcute (runnableImpl1 );}} private class RunnableImpl1 implements Runnable {@ Overridepublic void run () {System. out. println ("Thread name:" + Thread. currentThread (). getName ());}} //////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /// // /// NewSingleThreadExecutor () use * to create a thread pool that only contains one thread. It only uses this unique working thread to execute the task. * This ensures that all tasks are executed in the specified sequence (FIFO. ** this feature is of practical significance. **/private void testExecutors2 () {Executor executor = Executors. newSingleThreadExecutor (); RunnableImpl2 runnableImpl2 = null; for (int I = 0; I <15; I ++) {runnableImpl2 = new Runna BleImpl2 ("" + I )executor.exe cute (runnableImpl2);} private class RunnableImpl2 implements Runnable {private String name; private RunnableImpl2 (String name) {this. name = name ;}@ Overridepublic void run () {System. out. println ("thread name:" + name );}} //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /// // *** thread pool (Executors) and Fut UreTask combination use */private void testExecutors3 () {ExecutorService executorService = Executors. newFixedThreadPool (5); ArrayList <FutureTask> futureTaskArrayList = new ArrayList <FutureTask> (); CallableImpl callableImpl = null; FutureTask futureTask = null; for (int I = 0; I <10; I ++) {callableImpl = new CallableImpl (); futureTask = new FutureTask (callableImpl); // execute futuretaskexecutorservice.exe cute (futureTask ); // Save each FutureTask to the collection to obtain the corresponding result. futureTaskArrayList. add (futureTask);} // traverses the set to obtain the execution result of each FutureTask. try {for (Iterator <FutureTask> iterator = futureTaskArrayList. iterator (); iterator. hasNext ();) {FutureTask ft = (FutureTask) iterator. next (); // it will not be called to ft until the calculation of the FutureTask is completed. get () while (! Ft. isDone (); System. out. println ("-----> return result:" + ft. get () ;}} catch (Exception e) {}}///////////////////////////////////// ///////////////////////////////////}

CallableImpl is as follows:

package cc.vv;import java.util.Random;import java.util.concurrent.Callable;public class CallableImpl implements Callable<Integer> {public CallableImpl() {}@Overridepublic Integer call() throws Exception {int result=new Random().nextInt(100);System.out.println(""+Thread.currentThread().getName());return Integer.valueOf(result);}}


Main. xml is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>



ExecutorsnewCachedThreadPool (); different from ExecutorsnewFixedThreadPool (int n );

Public static ExecutorService newCachedThreadPool () creates a thread pool that can create new threads as needed, but it will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. Calling execute will reuse the previously constructed thread (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can use the ThreadPoolExecutor constructor to create a thread pool with similar attributes but different details (such as timeout parameters.

Public static ExecutorService newFixedThreadPool (int nThreads) creates a thread pool that can reuse a fixed number of threads and runs these threads in a shared unbounded queue. At any point, most nThreads threads are in the active state of processing tasks. If an additional task is submitted when all threads are active, the additional task will wait in the queue before there is an available thread. If any thread is terminated due to a failure during the execution before it is disabled, a new thread will execute subsequent tasks (if needed) in place of it ). Before a thread is explicitly disabled, the thread in the pool will always exist.

JAVA thread pool example: Executors

// Statement
ExecutorService pool = new ThreadPoolExecutor (100,100, 0L, TimeUnit. NANOSECONDS, new LinkedBlockingQueue <Runnable> ()){
@ Override
Protected void afterExecute (Runnable runnable, Throwable throwable ){
Super. afterExecute (runnable, throwable );
If (throwable! = Null ){
If (throwable. getMessage ()! = Null ){
If (throwable. getMessage (). indexOf ("Timeout waiting for value ")! =-1)
Execute (runnable );
Else {
System. err. println (throwable );
}
}
}
}
@ Override
Protected void terminated (){
Super. terminated ();
System. out. println (System. currentTimeMillis ()-start_time );
System. exit (0 );
}
};
// Call
Pool.exe cute (new Runnable (){
Public void run (){
GetCache (). put (key, value );
}
});
I don't know if I can understand it.
 

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.