在开始之前,我还是先说一下Callable、Future和FutureTask,还有就是线程框架ExecutorService;
一、Callable用途及实践
- 说到Callable,那肯定得提一下Runnable,他两者的区别在与Callable可以通过FutureTask获取异步线程返回值,而Runnable无法拿到返回值。
- Callable的call方法可以抛出异常,而Runnable的run方法不能抛出异常。
介绍一下Callable与Runnable使用:
public static void main(String[] args) {
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<List> future = executorService.submit(new hrxCallnable());
Future future1 = executorService.submit(new hrxRunnable());
try {
System.out.println(future.get());
System.out.println(future1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
/**
* 模拟Callable方法
*/
public static class hrxCallnable implements Callable<List> {
@Override
public List call() throws Exception {
try {
//模拟阻塞
Thread.sleep(3000);
List list = new ArrayList();
String heruixing = "何瑞星";
list.add(heruixing);
System.out.println("模拟Callable完成!");
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* 模拟Runable方法
*/
public static class hrxRunnable implements Runnable {
@Override
public void run() {
try {
//模拟阻塞
Thread.sleep(3000);
System.out.println("模拟Runable完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、FutureTask 的特性以及和Future的区别
FutureTask 实现了 Future接口。
最主要的特性是,相同的FutureTask对象,只会被执行一次,来保证任务的唯一性,且线程安全。
Future模式简述
传统单线程环境下,调用函数是同步的,必须等待程序返回结果后,才可进行其他处理。 Futrue模式下,调用方式改为异步。
Futrue模式的核心在于:充分利用主函数中的等待时间,利用等待时间处理其他任务,充分利用计算机资源。
所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。
JDK5新增了Future接口,用于描述一个异步计算的结果。虽然 Future 以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的 CPU 资源,而且也不能及时地得到计算结果。
Future:
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果等操作。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
public interface Future<V> {
/**
* 方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。
*
* @param mayInterruptIfRunning 表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。
* @return 如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;
* 如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;
* 如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* 方法表示任务是否被取消成功
* @return 如果在任务正常完成前被取消成功,则返回 true
*/
boolean isCancelled();
/**
* 方法表示任务是否已经完成
* @return 若任务完成,则返回true
*/
boolean isDone();
/**
* 方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回
* @return 任务执行的结果值
* @throws InterruptedException
* @throws ExecutionException
*/
V get() throws InterruptedException, ExecutionException;
/**
* 用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null(并不是抛出异常,需要注意)。
* @param timeout 超时时间
* @param unit 超时单位
* @return
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
从上面方法的注释可以看出,Futrue提供了三种功能:
1)判断任务是否完成;
2)能够中断任务;
3)能够获取任务执行结果。(最为常用的)
因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask(JDK8以前唯一实现类)。
FutureTask
public class FutureTask
public interface RunnableFuture
由此看出FutureTask它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
FutureTask提供了2个构造器:
// 包装callable
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
//把Runable转换成callable来处理(结果尽然让传进来,所以这个方法没啥用)
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。
FutureTask实现了Futrue可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。
举个栗子
直接使用Futrue来接收返回值:(结合callable)
public static void main(String args[]) {
Instant start = Instant.now();
ExecutorService executor = Executors.newCachedThreadPool();
//执行callable任务 拿到但绘制result
Future<Integer> result = executor.submit(() -> {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++)
sum += i;
return sum;
});
Instant mid = Instant.now();
System.out.println("Mid拿到Futrue结果对象result:" + Duration.between(start, mid).toMillis());
try {
System.out.println("task运行结果计算的总和为:" + result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
Instant end = Instant.now();
System.out.println("End拿到结果值:" + Duration.between(start, end).toMillis());
}
输出:
子线程在进行计算
Mid拿到Futrue结果对象result:98
task运行结果计算的总和为:4950
End拿到结果值:3099
我们很显然可以发现,mid的时间很短,主线程马上向下执行了,但是end的时间就比较长了,因此get()拿结果属于阻塞方法。
FutureTask获取结果:(结合Callbale使用)
public static void main(String args[]) {
Instant start = Instant.now();
ExecutorService executor = Executors.newCachedThreadPool();
//使用FutureTask包装callbale任务,再交给线程池执行
FutureTask<Integer> futureTask = new FutureTask<>(() -> {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++)
sum += i;
return sum;
});
//线程池执行任务 这个返回值不需要了,直接就在futureTask对象里面了
executor.submit(futureTask);
Instant mid = Instant.now();
System.out.println("Mid拿到futureTask结果对象result:" + Duration.between(start, mid).toMillis());
try {
System.out.println("task运行结果计算的总和为:" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
Instant end = Instant.now();
System.out.println("End拿到结果值:" + Duration.between(start, end).toMillis());
}
输出:
子线程在进行计算
Mid拿到futureTask结果对象result:86
task运行结果计算的总和为:4950
End拿到结果值:3088
第二种方式(只是进行了简单包装而已):
//第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
FutureTask
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++)
sum += i;
return sum;
});
Thread thread = new Thread(futureTask);
thread.start();
Callable和Futrue的区别:Callable用于产生结果,Future用于获取结果
ExecutorService介绍及使用
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
(1). newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(index);
}
});
}
线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
(2). newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。可参考PreloadDataCache。
(3) newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:****
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
表示延迟3秒执行。
定期执行示例代码如下:
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
@Overridepublic void run() {System.out.println("delay 1 seconds, and excute every 3 seconds");}}, 1, 3, TimeUnit.SECONDS);
表示延迟1秒后每3秒执行一次。
ScheduledExecutorService比Timer更安全,功能更强大,后面会有一篇单独进行对比。
(4)、newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
最后回到并发编程之多数据集合下获取返回值实例:
//创建10个线程池
ExecutorService executorService =Executors.newFixedThreadPool(10);
//加载业务数据集合
Callable<List> trainerListCallable = () -> trainerPersonService.findTrainerPersonList(trainerPersonReq);
//get Callable加载的业务数据
FutureTask<List> trainerListTask = new FutureTask<>(trainerListCallable);
//接收 call()方法返回值
executorService.submit(trainerListTask);