Executor框架

java中的线程即使是工作单元也是执行机制,从JDK5后,工作单元与执行机制分离。工作单元包括Runnable和Callable,执行

机制由JDK5中增加的java.util.concurrent包中Executor框架提供。
HotSpot VM的线程模型中将java的线程映射为本地操作系统的线程,java线程的启动意味着一个本地操作系统的创建,而

java线程的终止也就意味着对应的系统线程的回收。
Executor框架主要包含三个部分:

任务:包括Runnable和Callable,其中Runnable表示一个可以异步执行的任务,而Callable表示一个会产生结果的任务

任务的执行:包括Executor框架的核心接口Executor以及其子接口ExecutorService。在Executor框架中有两个关键类

ThreadPoolExecutor和ScheduledThreadPoolExecutor实现了ExecutorService接口。

new Thread()的缺点
每次new Thread()耗费性能
调用new Thread()创建的线程缺乏管理,被称为野线程,而且可以无限创建,之间相互竞争,会导致过多占用系统资源导致

系统瘫痪。不利于扩展,比如定时执行、定期执行、线程中断
采用线程池的有点
重用存在的线程,减少对象创建、消亡的开销,性能佳
可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞
提供定时执行、定期执行、单线程、并发数控制等功能
Executor框架便是java5中引入的,
其内部使用了线程池机制,它在java.util.cocurrent包下,通过该框架来控制线程的启动、执行和关闭,可以简化并发编程

的操作。因此,在java5之后,通过Exector来启动一个线程比使用Thread的start方法更好,除了更易管理,效率更好(用线

程池实现,节约开销)外,还有关键的一点:有助于避免this逃逸问题–如果我们在构造器中启动一个线程,因为另一个任

务可能会在构造器结束之前开始执行,此时可能会访问到初始化了一半的对象用Executor在构造器中。
Executor框架包括:线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。
Executors方法介绍
Executors工厂类
通过Executors提供四种线程池,newFixedThreadPool、newCachedThreadPool、newSingleThreadExecutor、

newScheduledThreadPool.
1.public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
2.public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新

线程并添加到池中。终止并从缓存中移除那些已60秒钟未被使用的线程 。
3.public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。、
4.public static ScheduleExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来代替Timer类。
1.newFixedThreadPool创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i=0;i<20;i++){

Runnable synRunnable = new Runnable(){
public void run(){

    Log.e(TAG,Thread.currentThread().getName());

}

};
executorService.execute(syncRunnable);
}
运行结果:总共只会创建5个线程,开始执行五个线程,当五个线程都处于活动状态,再次提交的任务都会加入队列等到其他

线程运行结束,当线程处于空闲状态时会被下一个任务复用
2.newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=0;i<100;i++){

Runnable syncRunnable = new Runnable(){

public void run(){

Log.e(TAG,Thread.currentThread().getName());

}

}
executorService.execute(syncRunnable);
}

运行结果:可以看出缓存线程池大小是不定值,可以需要创建不同数量的线程,在使用缓存型池时,先查看池中有没有以前

创建的线程,如果有,就复用,如果没有,就新建新的线程加入池中,缓存型池子通常用于执行一些生存期很短的异步型任

务。

3.newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行
schedule(Runnable command,long delay,TimeUnit unit)创建并执行在给定延迟后启用的一次性操作
实例:表示从提交任务开始计时,5000毫秒后执行
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
for(int i=;i<20;i++){

Runnable syncRunnable = new Runnable(){

	public void run(){

	Log.e(TAG,Thread.currentThread().getName());

}
};

executorService.schedule(synchRunnable,5000,TimeUnit.MILLISECONDS);
}

运行结果和newFixedThreadPool类似,不同的是newScheduledThread是延时一定时间之后才执行
scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnitunit)
创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在initialDelay后开始执行,

然后在initialDelay+period后执行,接着在initialDelay+2*period后执行,依次类推
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
Runnable syncRunnable = new Runnable(){

public void run(){

Log.e(TAG,Thread.currentThread().getName());
}
};
executorService.scheduleAtFixedRate(syncRunnable,5000,3000,TimeUnit.MILLISECONDS);

scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)
创建并执行一个在给定初始延迟后首次的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
Runnable syncRunnable = new Runnable(){

public void run(){

Log.e(TAG,Thread.currentThread().getName());
try{
          Thread.sleep(1000);
}catch(InterruptedException e){
	e.printStackTrace()
    }

}

};
executorService.scheduleWithFixedDelay(syncRunnable,5000,3000,TimeUnit.MILLISECONDS);
4.newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序

(FIFO,LIFO,优先级)执行
ExecutorService executorService = Executors.newSingleThreadExecutor();
for(int i=0;i<20;i++){

Runnable syncRunnable = new Runnable(){

public void run(){

Log.e(TAG,Thread.currentThread().getName());
 }

}
executorService.execute(syncRunnable);
}

运行结果:只会创建一个线程,当上一个执行完之后才会执行第二个

ExecutorService
ExecutorService是一个接口,ExecutorService接口继承了Executor接口,定义了一些生命周期的方法。
public interface ExecutorSerice extends Executor{

void shutdown();//顺次地关闭ExecutorService,停止接收新的任务,等待所有已经提交的任务执行完毕之后,关

闭ExecutorService
List shutdown();//阻止等待任务启动并试图停止当前正在执行的任务,停止接收新的任务,返回处于

等待的任务列表
boolean isShutdown();//判断线程池是否已经关闭
boolean isTerminated();//如果关闭后所有任务都已完成,则返回true.注意,除非首先调用shutdown或

shutdownNow,否则isTerminated永不为true.
boolean awaitTermination(long timeout,timeUnit unit)//等待阻塞直到关闭或发生中断,timeout-最长等待时

间,unit-timeout参数的时间单位 如果此执行程序终止,则返回true;如果终止前超时期满,则返回false

}
Executor作为灵活 且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程

和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务的线程相当于消费者,并用

Runnable来表示任务,Executeor的实现还提供了对生命周期的支持,以及统计信息收集,应用程序管理机制和性能监视等机

制。

1.Executor简介

在这里插入图片描述
Executor:一个接口,其定义了一个接收Runnable对象的方法executor,其方法签名为executor(Runnable command),
ExecutorSerice:是一个比Executor使用更广泛的子类接口,其提供了生命周期管理的方法,以及可跟踪一个或多个异步任务

执行状况返回Future的方法
AbstractExecutorService:ExecutorService执行方法的默认实现
ScheduledExecutorService:一个可定时调度任务的接口
ScheduledThreadPoolExecutor:ScheduledExecutorService的实现,一个定时调度任务的线程池
ThreadPoolExecutor:线程池,可以通过调用Executors以下静态工厂方法来创建线程池并返回一个ExecutorService对象:
2.ThreadPoolExecutor构造函数的各个参数说明
ThreadPoolExecutor方法签名:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) //后两个参数为可选参数
参数说明:
corePoolSize:核心线程数,如果运行的线程少于corePoolSize,则创建新线程来执行新任务,即使线程是空闲的
maximumPoolSize:最大线程数,可允许创建的线程数,corePoolSize和maximumPoolSize设置得边界自动调整池大小:
corePoolSize<运行的线程数<maximumPoolSize:仅当队列满时才创建新线程
corePoolSize=运行的线程数=maximumPoolSize:创建固定大小的线程池
keepAliveTime:如果线程数多于corePoolSize,则这些多余的线程的空闲时间超过keepAliveTime时将被终止
unit:keepAliveTime参数的时间单位
workQueue:保存任务的阻塞队列,与线程的大小有关:
当运行的线程数少于corePoolSize时,在有新任务时直接创建新线程来执行任务而无需再进队列
当运行的线程数等于或多于corePoolSize,在有新任务添加时则选加入队列,不直接创建线程
当队列满时,在有新任务时就创建新线程。
threadFactoy:使用ThreadFactory创建新线程,默认使用defaultThreadFactory创建线程
handle:定义处理被拒绝任务的策略,默认使用ThreadPoolExecutor.AbortPolicy,任务被拒绝时将抛出

RejectExecutorException

3.Executors:提供了一系列静态工厂方法用于创建各种线程池
newFixedThreadPool:创建可重用且固定线程数的线程池,如果线程池中的所有线程都处于活动状态,此时再提交任务就在队

列中等待,直到有可用线程;如果线程池中的某个线程由于异常而结束时,线程池就会再补充一条新线程。
方法签名:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
//使用一个基于FIFO排序的阻塞队列,在所有corePoolSize线程都忙时新任务将在队

列中等待
new LinkedBlockingQueue());
}

newSingleThreadExecutor:创建一个单线程的Executor,如果该线程因为异常而结束就新建一条线程来继续执行后续任务
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
//corePoolSize和maximumPoolSize都等于,表示固定线程池大小为1
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}

newScheduledThreadPool:创建一个延迟执行或定期执行的线程池
方法签名:
public static ScheduleExecutorService newScheduledThreadPool(int corePoolSize){

return new ScheduleThreadPoolExecutor(corePoolSize);

}

public ScheduledThreadPoolExecutor(int corePoolSize){

super(corePoolSize,Integer.MAX_VALUE,0,TimeUnit.NANOSECONDS,new DelayedWorkQueue());

}

例1:使用newScheduledThreadPool来模拟心跳机制

public class HeartBeat{

public static void main(String[] args){

ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
Runnable task = new Runnable(){

	public void run(){

		System.out.println("HeartBeat................");
	}

};
executor.scheduleAtFixedRate(task,5,3,TimeUnit.SECONDS);//5秒后第一次执行,之后每隔3秒执行一次

    }

}

输出:
HeartBeat… //5秒后第一次输出
HeartBeat… //每隔3秒输出一个

newCachedThreadPool:创建可缓存的线程池,如果线程池中的线程在60秒未被使用就将被移出,在执行新任务时,当线程池

中有之前创建的可用线程就重用可用线程,否则就新建一条线程

public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
//使用同步队列,将任务直接提交给线程
new SynchronousQueue());
}

public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool = Executors.newCachedThreadPool();//线程池里面的线程数会动态变化,并可在线程

线被移除前重用
for (int i = 1; i <= 3; i ++) {
final int task = i; //10个任务
//TimeUnit.SECONDS.sleep(1);
threadPool.execute(new Runnable() { //接受一个Runnable实例
public void run() {
System.out.println("线程名字: " + Thread.currentThread().getName() + " 任务名为:

"+task);
}
});
}
}
}

输出:(为每个任务新建一条线程,共创建了3条线程)
线程名字: pool-1-thread-1 任务名为: 1
线程名字: pool-1-thread-2 任务名为: 2
线程名字: pool-1-thread-3 任务名为: 3
去掉第6行的注释其输出如下:(始终重复利用一条线程,因为newCachedThreadPool能重用可用线程)
线程名字: pool-1-thread-1 任务名为: 1
线程名字: pool-1-thread-1 任务名为: 2
线程名字: pool-1-thread-1 任务名为: 3
通过使用Executor可以很轻易的实现各种调优 管理 监视 记录日志和错误报告等待。

Executor的生命周期
ExecutorService提供了管理Executor生命周期的方法,ExecutorService的生命周期包括了:运行关闭和终止三种状态。
ExecutorService在初始化创建时处于运行状态
shutdown方法等待提交的任务执行完成并不再接受新任务,在完成全部提交的任务后关闭
shutdownNow方法将强制终止所有运行中的任务并不再允许提交新任务

可以将一个Runnable(如例2)或Callable(如例3)提交给ExecutorService的submit方法执行,最终返回一上Futire用来获

得任务的执行结果或取消任务
例3:(任务执行完成后并返回执行结果)

public class CallableAndFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future future = executor.submit(new Callable() { //接受一上callable实例
public String call() throws Exception {
return “MOBIN”;
}
});
System.out.println(“任务的执行结果:”+future.get());
}
}

输出:
任务的执行结果:MOBIN

ExecutorCompletionService:实现了CompletionService,将执行完成的任务放到阻塞队列中,通过take或poll方法来获得执

行结果
例4:(启动10条线程,谁先执行完成就返回谁)

public class CompletionServiceTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(10); //创建含10.条线程的线程池
CompletionService completionService = new ExecutorCompletionService(executor);
for (int i =1; i <=10; i ++) {
final int result = i;
completionService.submit(new Callable() {
public Object call() throws Exception {
Thread.sleep(new Random().nextInt(5000)); //让当前线程随机休眠一段时间
return result;
}
});
}
System.out.println(completionService.take().get()); //获取执行结果
}
}

输出结果可能每次都不同(在1到10之间)
3

通过Executor来设计应用程序可以简化开发过程,提高开发效率,并有助于实现并发,在开发中如果需要创建线程可优先考

虑使用Executor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值