最简单的基本流程是:
- Callable任务通过ExecutorService来提交;
- 任务结束后返回的结果交给Future;
- Future通过get()方法去获得实际的运算结果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class Merge implements Callable<String>{
private String strA;
private String strB;
Merge(String strA, String strB){
this.strA = strA;
this.strB = strB;
}
@Override
public String call() throws Exception {
return strA+strB;
}
}
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newFixedThreadPool(1);
Merge task = new Merge("Hello " ,"World!");
Future<String> future = es.submit(task);
String result = future.get();
System.out.println(result);
es.shutdown();
}
}