Android thread pool (ii)--threadpoolexecutor and its rejection policy Rejectedexecutionhandler use example

Source: Internet
Author: User

Mainactivity as follows:
Package Cc.vv;import Java.util.concurrent.linkedblockingqueue;import Java.util.concurrent.ThreadPoolExecutor; Import Java.util.concurrent.timeunit;import Android.os.bundle;import android.app.activity;/** * Demo Description: * Thread pool ( Threadpoolexecutor) and its deny policy (Rejectedexecutionhandler) Use the example * * Working principle: * thread pool work mainly involves: Corepoolsize,workqueue, Maximumpoolsize,rejectedexecutionhandler * Their invocation principle: * 1 when thread pool threads are less than corepoolsize create threads and process requests * 2 When the number of threads in the thread pool equals corepoolsize The request is placed in Workqueue, the idle thread in the thread pool takes the task from workqueue and processes * 3 when the workqueue is full of new tasks, the new thread is pooled and the request is processed; * If thread pool threads are greater than maximumpoolsize, use Rejectedexecutionhandler with a certain policy to deny processing * * There is also a keepalivetime in this mechanism, the document is described as follows: * When the numb Er of threads is greater than the core, * This is the maximum time that excess idle threads would wait for new tasks befor e terminating. * What does it mean? * For example, there are 5 threads in a thread pool, 3 of which are core threads (cores) and two are non-core threads. * When a non-core thread is still idle for a certain time (keepalivetime) (i.e. no task is performed or no task is executed) then the non-core thread is terminated. * The maximum amount of time that a non-core and idle thread in a thread pool can last, and the thread is terminated after that time. * * * * Rejectedexecutionhandler four rejection strategies * * HREADPOOlexecutor.abortpolicy: * Throws an Java.util.concurrent.RejectedExecutionException exception when the number in the thread pool equals the maximum number of threads. * Tasks involving this exception will not be executed. * * Threadpoolexecutor.callerrunspolicy (): * Retry adding the current task when the number in the thread pool equals the maximum number of threads; it will automatically repeat the Execute () method * * Threadpoolexecutor.discardoldestpolicy (): * When the number of thread pools equals the maximum number of threads, discards the task of the head of the work queue in the thread pool (that is, the task that waits for the longest time oldest) and executes the new incoming task * Threadpoolexecutor.discardpolicy (): * Discard new add-on tasks that cannot be performed when the number of threads in the pool equals the maximum number of threads * Reference: * http://blog.csdn.net/cutesource/ article/details/6061229 * http://blog.csdn.net/longeremmy/article/details/8231184 * http://blog.163.com/among_1985 /blog/static/275005232012618849266/* http://blog.csdn.net/longeremmy/article/details/8231184 * http://ifeve.com/ java-threadpool/* http://www.blogjava.net/xylz/archive/2010/07/08/325587.html * http://blog.csdn.net/ns_code/ article/details/17465497 * Thank very much * */public class Mainactivity extends Activity {@Overrideprotected void on Create (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); TestRejEctedexecutionhandler ();} Here you test four strategies, replacing the last parameter of the Threadpoolexecutor () method. private void Testrejectedexecutionhandler () {int Producetaskmaxnumber = 10;//Constructs a thread pool threadpoolexecutor threadpoolexecutor = new Threadpoolexecutor (2, 4, 3, Timeunit.seconds, New Linkedblockingqueue<runnable> (3), New Threadpoolexecutor.discardpolicy ()); for (int i = 1; i <= Producetaskmaxnumber; i++) {try {String task = "task" + i; System.out.println ("put" + task + "into thread pool"); Threadpoolexecutor.execute (New Runnableimpl (Task));} catch (Exception e) {e.printstacktrace (); System.out.println ("AbortPolicy policy throws Exception---->" + e.tostring ());}}} Private class Runnableimpl implements Runnable {private String taskname;private int consumertasksleeptime = 2000; Runnableimpl (String taskname) {this.taskname = TaskName;} public void Run () {System.out.println ("start" + taskname); try {//Simulate time-consuming task Thread.Sleep (consumertasksleeptime);} catch (Exception e) {e.printstacktrace ();} System.out.println ("complete" + TaskName);}}}

Main.xml 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>


Android thread pool (ii)--threadpoolexecutor and its rejection policy Rejectedexecutionhandler use example

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.