java多线程之Callable跟Future

1、首先说一下创建线程的方式

  • new Thread跟实现Runnable接口的弊端
    (1)、每次new Thread新建对象性能差。
    (2)、线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
    (3)、缺乏更多功能,如定时执行、定期执行、线程中断。
    (4)、最大的一个弊端就是这两种方式在执行完任务之后无法获取执行结果。
    (5)、如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。

2、Callable和Future出现的原因

而自从Java 1.5开始,就提供了Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果。

Callable和Future介绍

(1)、Callable接口代表一段可以调用并返回结果的代码。
(2)、Future接口表示异步任务,是还没有完成的任务给出的未来结果。
(3)、所以说Callable用于产生结果,Future用于获取结果。

Callable接口使用泛型去定义它的返回类型。Executors类提供了一些有用的方法在线程池中执行Callable内的任务。由于Callable任务是并行的(并行就是整体看上去是并行的,其实在某个时间点只有一个线程在执行),我们必须等待它返回的结果。

Callable与Runnable的对比

Runnable它是一个接口,在它里面只声明了一个run()方法:

1public interface Runnable { 2 public abstract void run(); 3}

由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。

Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做call():

1public interface Callable<V> { 2 /** 3 * Computes a result, or throws an exception if unable to do so. 4 * 5 * [@return](https://my.oschina.net/u/556800) computed result 6 * [@throws](https://my.oschina.net/throws) Exception if unable to compute a result 7 */ 8 V call() throws Exception; 9}

可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。

那么怎么使用Callable呢?

一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:

1<T> Future<T> submit(Callable<T> task); 2<T> Future<T> submit(Runnable task, T result); 3Future<?> submit(Runnable task);

第一个submit方法里面的参数类型就是Callable

暂时只需要知道Callable一般是和ExecutorService配合来使用的,具体的使用方法讲在后面讲述。 一般情况下我们使用第一个submit方法和第三个submit方法,第二个submit方法很少使用。

Future的介绍

Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
Future类位于java.util.concurrent包下,它是一个接口:

1public interface Future<V> { 2 boolean cancel(boolean mayInterruptIfRunning); 3 boolean isCancelled(); 4 boolean isDone(); 5 V get() throws InterruptedException, ExecutionException; 6 V get(long timeout, TimeUnit unit) 7 throws InterruptedException, ExecutionException, TimeoutException; 8}

在Future接口中声明了5个方法,下面依次解释每个方法的作用:

  • cancel:
    用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true

  • isCancelled:
    表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。

  • isDone:
    表示任务是否已经完成,若任务完成,则返回true;

  • get():
    用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回。

  • get(long timeout, TimeUnit unit): 用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。

也就是说Future提供了三种功能:

  • 判断任务是否完成;
  • 能够中断任务;
  • 能够获取任务执行结果。

因为Future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的FutureTask。

FutureTask介绍

FutureTask实现了RunnableFuture接口,这个接口的定义如下:

1public interface RunnableFuture<V> extends Runnable, Future<V> { 2 void run(); 3}

可以看到这个接口实现了Runnable和Future接口,接口中的具体实现由FutureTask来实现。这个类的两个构造方法如下 :

1 public FutureTask(Callable<V> callable) { 2 if (callable == null) 3 throw new NullPointerException(); 4 sync = new Sync(callable); 5 } 6 public FutureTask(Runnable runnable, V result) { 7 sync = new Sync(Executors.callable(runnable, result)); 8 }

如上提供了两个构造函数,一个以Callable为参数,另外一个以Runnable为参数。这些类之间的关联对于任务建模的办法非常灵活,允许你基于FutureTask的Runnable特性(因为它实现了Runnable接口),把任务写成Callable,然后封装进一个由执行者调度并在必要时可以取消的FutureTask。

FutureTask可以由执行者调度,这一点很关键。它对外提供的方法基本上就是Future和Runnable接口的组合:get()、cancel、isDone()、isCancelled()和run(),而run()方法通常都是由执行者调用,我们基本上不需要直接调用它。

3、FutureTask实例

1public class MyCallable implements Callable<String> { 2 private long waitTime; 3 public MyCallable(int timeInMillis){ 4 this.waitTime=timeInMillis; 5 } 6 [@Override](https://my.oschina.net/u/1162528) 7 public String call() throws Exception { 8 Thread.sleep(waitTime); 9 //return the thread name executing this callable task 10 return Thread.currentThread().getName(); 11 } 12 13} 14public class FutureTaskExample { 15 public static void main(String[] args) { 16 ExecutorService executor = Executors.newFixedThreadPool(2); // 创建线程池并返回ExecutorService实例 17 MyCallable callable1 = new MyCallable(1000); // 要执行的任务 18 MyCallable callable2 = new MyCallable(2000); 19 FutureTask<String> futureTask1 = new FutureTask<String>(callable1);// 将Callable写的任务封装到一个由执行者调度的FutureTask对象 20 FutureTask<String> futureTask2 = new FutureTask<String>(callable2); 21 executor.execute(futureTask1); // 执行任务 22 executor.execute(futureTask2); 23 24 25 或者执行下面的方法 26 ExecutorService executor = Executors.newFixedThreadPool(2); // 创建线程池并返回ExecutorService实例 (单例的) 27 MyCallable callable1 = new MyCallable(1000);//线程1 28 MyCallable callable2 = new MyCallable(2000);线程2 29 Future<String> s1 = executor.submit(callable1);//会创建FutureTask 并且会执行execute方法 30 Future<String> s2 = executor.submit(callable2);//会创建FutureTask 并且会执行execute方法 31 while (true) { 32 try { 33 if(futureTask1.isDone() && futureTask2.isDone()){// 两个任务都完成 34 System.out.println("Done"); 35 executor.shutdown(); // 关闭线程池和服务 36 return; 37 } 38 39 if(!futureTask1.isDone()){ // 任务1没有完成,会等待,直到任务完成 40 System.out.println("FutureTask1 output="+futureTask1.get()); 41 } 42 43 System.out.println("Waiting for FutureTask2 to complete"); 44 String s = futureTask2.get(200L, TimeUnit.MILLISECONDS); 45 if(s !=null){ 46 System.out.println("FutureTask2 output="+s); 47 } 48 } catch (InterruptedException | ExecutionException e) { 49 e.printStackTrace(); 50 }catch(TimeoutException e){ 51 //do nothing 52 } 53 } 54 } 55}

运行如上程序后,可以看到一段时间内没有输出,因为get()方法等待任务执行完成然后才输出内容.

输出结果如下:

1FutureTask1 output=pool-1-thread-1 2Waiting for FutureTask2 to complete 3Waiting for FutureTask2 to complete 4Waiting for FutureTask2 to complete 5Waiting for FutureTask2 to complete 6Waiting for FutureTask2 to complete 7FutureTask2 output=pool-1-thread-2 8Done

综上所述,Callable和Future的出现是为了让线程变得可以控制,并且可以返回线程执行的结果

项目中的使用实例,多线程导入学员信息

1.创建线程池

1/** 2 * Created by ds on 2017/6/29. 3 */ 4[@Component](https://my.oschina.net/u/3907912) 5public class ThreadPool4ImportStudent { 6 7 volatile private static ExecutorService instance = null; 8 9 private ThreadPool4ImportStudent(){} 10 11 public static ExecutorService getInstance() { 12 try { 13 if(instance != null){ 14 15 }else{ 16 Thread.sleep(300); 17 synchronized (ThreadPool4ImportStudent.class) { 18 if(instance == null){ 19 instance = Executors.newFixedThreadPool(10); 20 } 21 } 22 } 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 return instance; 27 } 28}

上面的方法 创建了线程池,并且注入了相关的mapper类

2.创建线程

1public class ThreadImportStudents implements Callable<List<Integer>> { 2 3 public static final String IMPORT_TYPE_STUDENT = "IMPORT_TYPE_STUDENT"; 4 public static final String IMPORT_TYPE_VIP = "IMPORT_TYPE_VIP"; 5 Log log_student = LogFactory.getLog("student"); 6 List<Integer> ids = new ArrayList<>(); 7 private String type; 8 private Map<String, List<String>> allStudents; 9 private List<ImportRowVo> students; 10 private Integer userId; 11 private Integer vipRecordId; 12 private boolean is_custom; 13 private StudentImportRecord record; 14 15 private Date date = new Date(); 16 private Map<String, ImportFieldVo> importTemplateMap; 17 private Integer companyId; 18 private Integer schoolId; 19 20 public ThreadImportStudents(String type, Map<String, List<String>> allStudents, Map<String, ImportFieldVo> importTemplateMap, List<ImportRowVo> students, 21 Integer userId, StudentImportRecord record, Integer vipRecordId, boolean is_custom, Integer companyId, Integer schoolId) { 22 this.type = type; 23 this.allStudents = allStudents; 24 this.importTemplateMap = importTemplateMap; 25 this.students = students; 26 this.userId = userId; 27 this.record = record; 28 this.vipRecordId = vipRecordId; 29 this.is_custom = is_custom; 30 this.companyId = companyId; 31 this.schoolId = schoolId; 32 } 33 34 [@Override](https://my.oschina.net/u/1162528) 35 public List<Integer> call() throws Exception { 36 try { 37 return insertOrUpdate(); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 return null; 42 } 43}

上面的类是属于批量添加学员的线程类,实现了Callable接口并重写了call方法,返回所有插入学员的id集合。

3、业务类通过Future控制线程

1List<Integer> studentIds = new ArrayList<Integer>(); 2List<Future<List<Integer>>> ids = new ArrayList<Future<List<Integer>>>(); 3Future<List<Integer>> stuId = ThreadPool4ImportStudent.getInstance().submit(new ThreadImportStudents(type, allStudents, importTemplateMap, 4 student_list, userId, record, vo.getId(), is_custom, students.getCompanyId(), students.getSchoolId())); 5ids.add(stuId); 6for (Future<List<Integer>> id:ids) { 7 try { 8 List<Integer> idl=id.get(); 9 if(idl!=null){ 10 for(Integer idi:idl){ 11 if(idi==null){ 12 error++; 13 } 14 } 15 studentIds.addAll(idl); 16 } 17 }catch (Exception e){} 18}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

java多线程之Callable跟Future - HelloWorld