Callable、Future和FutureTask区别实践《并发编程》
原创
©著作权归作者所有:来自51CTO博客作者liuyunshengsir的原创作品,请联系作者获取转载授权,否则将追究法律责任
实现原理
从下图可以看出Runnable 和Callable都是函数式接口(函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。),一般使用都结合线程池进行使用。
异步线程的实现(非线池方式)
package com.lys.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* @Auther: liuysh
* @Date: 2021/9/18 15:02
* @Description:
*/
public class MyFutureTaskTest {
public static void main(String[] args) throws Exception{
Callable<Integer> aCallable =()->10;
Callable<Integer> bCallable =()->20;
FutureTask<Integer> aFutureTask = new FutureTask<>(aCallable);
FutureTask<Integer> bFutureTask = new FutureTask<>(bCallable);
new Thread(aFutureTask).start();
new Thread(bFutureTask).start();
Integer a = aFutureTask.get();
Integer b = bFutureTask.get();
int c=a+b;
System.out.println("非线程池异步获取a+b=:" +c);
}
}
线程池的实现方式
package com.lys.thread;
import java.util.concurrent.*;
/**
* @Auther: liuysh
* @Date: 2021/9/18 11:24
* @Description:
*/
public class ThreadPoolTest {
public static void main(String[] args) throws Exception {
System.out.println("当前系统支持核心线程数:"+Runtime.getRuntime().availableProcessors());
ExecutorService executorService= Executors.newFixedThreadPool(2);
Callable<Integer> aCallable=()->1;
Callable<Integer> bCallable=()->1;
Future<Integer> aFuture= executorService.submit(aCallable);
Future<Integer> bFuture= executorService.submit(bCallable);
Integer a = aFuture.get();
Integer b = bFuture.get();
int c=a+b;
System.out.println("线程池异步获取a+b=:" +c);
executorService.shutdown();
}
}