【Android】小白进阶之线程池浅析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liwei16611/article/details/82344907

由于项目推动,开始学习线程池相关内容,希望对你有益。

1、基础概念浅析

在使用线程的过程中如果并发线程数量很多,并且每个线程都是执行一个时间很短的任务就结束

这样频繁创建线程就会大大降低系统的效率,而线程池就可以解决这个问题

1.1、核心方法:

public ThreadPoolExecutor( int corePoolSize,
						   int maximumPoolSize,
                           long keepAliveTime,
                           TimeUnit unit,
                           BlockingQueue workQueue,
                           ThreadFactory threadFactory,
                           RejectedExecutionHandler handler);

这是其中最重要的一个构造方法,这个方法决定了创建出来的线程池的各种属性,下面依靠一张图来更好的理解线程池和这几个参数:

1.2、参数解析:

corePoolSize就是线程池中的核心线程数量,这几个核心线程在没有用的时候也不会被回收

maximumPoolSize就是线程池中可以容纳的最大线程的数量

keepAliveTime就是线程池中除了核心线程之外的其他的最长可以保留的时间,也即非核心线程可以保留的最长的空闲时间

util就是计算空闲时间的一个单位

workQueue是等待队列,任务可以储存在任务队列中等待被执行,执行的是 FIFIO 原则

threadFactory是创建线程的线程工厂

handler是一种拒绝策略:

AbortPolicy:不执行新任务,直接抛出异常,提示线程池已满
DisCardPolicy:不执行新任务,也不抛出异常
DisCardOldSetPolicy:将消息队列中的第一个任务替换为当前新进来的任务执行
CallerRunsPolicy:直接调用execute来执行当前任务

1.3、线程池种类:

CachedThreadPool:

可缓存的线程池,该线程池中没有核心线程,非核心线程的数量为Integer.max_value,就是无限大,当有需要时创建线程来执行任务,没有需要时回收线程,适用于耗时少,任务量大的情况

SecudleThreadPool:

周期性执行任务的线程池,按照某种特定的计划执行线程中的任务,有核心线程,但也有非核心线程,非核心线程的大小也为无限大,适用于执行周期性的任务

SingleThreadPool:

只有一条线程来执行任务,适用于有顺序的任务的应用场景

FixedThreadPool:

定长的线程池,有核心线程,核心线程的即为最大的线程数量,没有非核心线程

2、示例

创建线程工厂:

package com.test.sdk.utils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class TestThreadFactory implements ThreadFactory
{

	private String mName = null;
	private int mPriority;
	private final AtomicInteger mNumber = new AtomicInteger();  // 创建的线程个数,每创建一个线程该值加一
	
	public TestThreadFactory(String name, int priority)
	{
		mName = name;
		mPriority = priority;
	}
	
	@Override
	public Thread newThread(Runnable r)
	{
		// TODO Auto-generated method stub
		return new Thread(r, mName +"-"+mNumber.getAndIncrement())
		{
			@Override
			public void run()
			{
				// TODO Auto-generated method stub
				android.os.Process.setThreadPriority(mPriority); // 设置线程优先级
				super.run();
			}
		};
	}
}

创建线程池:

package com.test.sdk.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool
{
	private final static int POOL_SIZE 		 = 4;	// 线程池的大小,设置成为CUP核数2N
	private final static int MAX_POOL_SIZE 	 = 4;	// 设置线程池的最大线程数
	private final static int KEEP_ALIVE_TIME = 4;	// 设置线程的存活时间

	private ExecutorService mExecutor;
	
	private static TestThreadPool instance = new TestThreadPool();
	
	public static TestThreadPool getInstance() {
		
		return instance;
	}
	
	public TestThreadPool(){
		
		// 创建线程池工厂,
		// 第一个参数是线程池名字
		// 第二个参数是线程池优先级,THREAD_PRIORITY_BACKGROUND 为标准后台程序优先级
		ThreadFactory factory = new TestThreadFactory("sodo-thread-pool", android.os.Process.THREAD_PRIORITY_BACKGROUND);
		
		//创建工作队列
		BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(4);  //Integer.MAX_VALUE
		
		//创建线程池
		mExecutor = new ThreadPoolExecutor(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, factory); 
	}
	
	//在线程池中执行线程
	public Future<?> submit(Runnable command){
		
		return mExecutor.submit(command);
	}
	
	public void shutdown(){
		
		mExecutor.shutdownNow();
	}
	
	public boolean isShutDown() {
		
		return mExecutor.isShutdown();
	}
}

使用线程池:

private TestRun tstRunnable = null;

// 创建线程
private class TestRun implements Runnable {
   
   @Override
   public void run() {
   
   }
}

tstRunnable = new TestRun();
TestThreadPool.getInstance().submit(tstRunnable);

refer:

https://www.cnblogs.com/dolphin0520/p/3932921.html
https://baijiahao.baidu.com/s?id=1609465299690233434&wfr=spider&for=pc

猜你喜欢

转载自blog.csdn.net/liwei16611/article/details/82344907
今日推荐