温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java多线程Callable跟Future对比

发布时间:2021-07-05 15:48:54 来源:亿速云 阅读:143 作者:chen 栏目:大数据

本篇内容介绍了“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()方法:

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){}
}

“java多线程Callable跟Future对比”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI