java多线程之Callable跟Future

Wesley13
• 阅读 476

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()方法:

public interface Runnable {
    public abstract void run();
}

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

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

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

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

那么怎么使用Callable呢?

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

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

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

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

Future的介绍

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

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

在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接口,这个接口的定义如下:

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

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

    public FutureTask(Callable<V> callable) {  
        if (callable == null)  
            throw new NullPointerException();  
        sync = new Sync(callable);  
    }  
    public FutureTask(Runnable runnable, V result) {  
        sync = new Sync(Executors.callable(runnable, result));  
    }  

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

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

3、FutureTask实例

public class MyCallable implements Callable<String> {  
    private long waitTime;   
    public MyCallable(int timeInMillis){   
        this.waitTime=timeInMillis;  
    }  
    [@Override](https://my.oschina.net/u/1162528)  
    public String call() throws Exception {  
        Thread.sleep(waitTime);  
        //return the thread name executing this callable task  
        return Thread.currentThread().getName();  
    }  

}  
public class FutureTaskExample {  
     public static void main(String[] args) {  
        ExecutorService executor = Executors.newFixedThreadPool(2);          // 创建线程池并返回ExecutorService实例  
        MyCallable callable1 = new MyCallable(1000);                         // 要执行的任务  
        MyCallable callable2 = new MyCallable(2000);  
        FutureTask<String> futureTask1 = new FutureTask<String>(callable1);// 将Callable写的任务封装到一个由执行者调度的FutureTask对象  
        FutureTask<String> futureTask2 = new FutureTask<String>(callable2);  
        executor.execute(futureTask1);  // 执行任务  
        executor.execute(futureTask2);    


        或者执行下面的方法
        ExecutorService executor = Executors.newFixedThreadPool(2);        // 创建线程池并返回ExecutorService实例  (单例的)
        MyCallable callable1 = new MyCallable(1000);//线程1
        MyCallable callable2 = new MyCallable(2000);线程2
        Future<String> s1 = executor.submit(callable1);//会创建FutureTask 并且会执行execute方法
        Future<String> s2 = executor.submit(callable2);//会创建FutureTask 并且会执行execute方法
    while (true) {  
            try {  
                if(futureTask1.isDone() && futureTask2.isDone()){//  两个任务都完成  
                    System.out.println("Done");  
                    executor.shutdown();                          // 关闭线程池和服务   
                    return;  
                }  

                if(!futureTask1.isDone()){ // 任务1没有完成,会等待,直到任务完成  
                    System.out.println("FutureTask1 output="+futureTask1.get());  
                }  

                System.out.println("Waiting for FutureTask2 to complete");  
                String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);  
                if(s !=null){  
                    System.out.println("FutureTask2 output="+s);  
                }  
            } catch (InterruptedException | ExecutionException e) {  
                e.printStackTrace();  
            }catch(TimeoutException e){  
                //do nothing  
            }  
        }  
    }  
}  

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

输出结果如下:

FutureTask1 output=pool-1-thread-1
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
FutureTask2 output=pool-1-thread-2
Done

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

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

1.创建线程池

/**
 * Created by ds on 2017/6/29.
 */
[@Component](https://my.oschina.net/u/3907912)
public class ThreadPool4ImportStudent {

    volatile private static ExecutorService instance = null;

    private ThreadPool4ImportStudent(){}

    public static ExecutorService getInstance() {
        try {
            if(instance != null){

            }else{
                Thread.sleep(300);
                synchronized (ThreadPool4ImportStudent.class) {
                    if(instance == null){
                        instance = Executors.newFixedThreadPool(10);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return instance;
    }
}

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

2.创建线程

public class ThreadImportStudents implements Callable<List<Integer>> {

    public static final String IMPORT_TYPE_STUDENT = "IMPORT_TYPE_STUDENT";
    public static final String IMPORT_TYPE_VIP = "IMPORT_TYPE_VIP";
    Log log_student = LogFactory.getLog("student");
    List<Integer> ids = new ArrayList<>();
    private String type;
    private Map<String, List<String>> allStudents;
    private List<ImportRowVo> students;
    private Integer userId;
    private Integer vipRecordId;
    private boolean is_custom;
    private StudentImportRecord record;

    private Date date = new Date();
    private Map<String, ImportFieldVo> importTemplateMap;
    private Integer companyId;
    private Integer schoolId;

    public ThreadImportStudents(String type, Map<String, List<String>> allStudents, Map<String, ImportFieldVo> importTemplateMap, List<ImportRowVo> students,
            Integer userId, StudentImportRecord record, Integer vipRecordId, boolean is_custom, Integer companyId, Integer schoolId) {
        this.type = type;
        this.allStudents = allStudents;
        this.importTemplateMap = importTemplateMap;
        this.students = students;
        this.userId = userId;
        this.record = record;
        this.vipRecordId = vipRecordId;
        this.is_custom = is_custom;
        this.companyId = companyId;
        this.schoolId = schoolId;
    }

    [@Override](https://my.oschina.net/u/1162528)
    public List<Integer> call() throws Exception {
        try {
              return insertOrUpdate();
        } catch (Exception e) {
          e.printStackTrace();
        }
            return null;
    }
}

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

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

List<Integer> studentIds = new ArrayList<Integer>();
List<Future<List<Integer>>> ids = new ArrayList<Future<List<Integer>>>();
Future<List<Integer>> stuId = ThreadPool4ImportStudent.getInstance().submit(new ThreadImportStudents(type, allStudents, importTemplateMap,
                    student_list, userId, record, vo.getId(), is_custom, students.getCompanyId(), students.getSchoolId()));
ids.add(stuId);
for (Future<List<Integer>> id:ids) {
    try {
            List<Integer> idl=id.get();
            if(idl!=null){
                 for(Integer idi:idl){
                        if(idi==null){
                            error++;
                        }
                    }
                    studentIds.addAll(idl);
             }
        }catch (Exception e){}
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
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
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
Java ExecutorService四种线程池及ThreadPoolExecutor机制
一、为什么使用线程池使用newThread执行多个线程有如下一些问题:每次newThread新建对象性能差。线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。缺乏更多功能,如定时执行、定期执行、线程中断。相比newThread,Java提供的四种线程池的好处在于:重用存在的线程,减
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
Java多线程学习笔记
Java中创建多线程的三种方法1、继承Thread类创建线程2、实现Runnable接口创建线程3、使用Callable和Future创建线程\
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这