首页 > 代码库 > Android线程池(二)——ThreadPoolExecutor及其拒绝策略RejectedExecutionHandler使用演示样例

Android线程池(二)——ThreadPoolExecutor及其拒绝策略RejectedExecutionHandler使用演示样例

MainActivity例如以下:
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描写叙述:
 * 线程池(ThreadPoolExecutor)及其拒绝策略(RejectedExecutionHandler)使用演示样例
 * 
 * 工作原理:
 * 线程池的工作中主要涉及到:corePoolSize,workQueue,maximumPoolSize,RejectedExecutionHandler
 * 它们的调用原理:
 * 1 当线程池中线程数量小于corePoolSize则创建线程,并处理请求
 * 2 当线程池中线程数量等于corePoolSize则把请求放入workQueue中,线程池中的的空暇线程就从workQueue中取任务并处理
 * 3 当workQueue已满存放不下新入的任务时则新建线程入池,并处理请求;
 *   假设线程池中线程数大于maximumPoolSize则用RejectedExecutionHandler使用一定的策略来做拒绝处理
 * 
 * 在该机制中另一个keepAliveTime,文档描写叙述例如以下:
 * when the number of threads is greater than the core, 
 * this is the maximum time that excess idle threads will wait for new tasks before terminating.
 * 它是什么意思呢?
 * 比方线程池中一共同拥有5个线程,当中3个为核心线程(core)其余两个为非核心线程.
 * 当超过一定时间(keepAliveTime)非核心线程仍然闲置(即没有运行任务或者说没有任务可运行)那么该非核心线程就会被终止.
 * 即线程池中的非核心且空暇线程所能持续的最长时间,超过该时间后该线程被终止.
 * 
 * 
 * RejectedExecutionHandler的四种拒绝策略
 * 
 * hreadPoolExecutor.AbortPolicy:
 * 当线程池中的数量等于最大线程数时抛出java.util.concurrent.RejectedExecutionException异常.
 * 涉及到该异常的任务也不会被运行.
 * 
 * ThreadPoolExecutor.CallerRunsPolicy():
 * 当线程池中的数量等于最大线程数时,重试加入当前的任务;它会自己主动反复调用execute()方法
 * 
 * ThreadPoolExecutor.DiscardOldestPolicy():
 * 当线程池中的数量等于最大线程数时,抛弃线程池中工作队列头部的任务(即等待时间最久Oldest的任务),并运行新传入的任务
 * 
 * ThreadPoolExecutor.DiscardPolicy():
 * 当线程池中的数量等于最大线程数时,丢弃不能运行的新加任务
 * 
 * 參考资料:
 * 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 you very much
 * 
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		testRejectedExecutionHandler();
	}

	// 在此分别測试四种策略,替换ThreadPoolExecutor()方法最后一个參数就可以.
	private void testRejectedExecutionHandler() {
		int produceTaskMaxNumber = 10;
		// 构造一个线程池
		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 = "任务" + i;
				System.out.println("将" + task + "放入线程池");
				threadPoolExecutor.execute(new RunnableImpl(task));
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("AbortPolicy策略抛出异常----> " + 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("開始 " + taskName);
			try {
				// 模拟耗时任务
				Thread.sleep(consumerTaskSleepTime);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("完毕 " + taskName);
		}

	}

}

main.xml例如以下:

<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线程池(二)——ThreadPoolExecutor及其拒绝策略RejectedExecutionHandler使用演示样例