实现Callable接口
package com.jia.concurrency.future;
import java.util.concurrent.Callable;
public class RealData implements Callable<String> {
private String para;
public RealData(String para) {
this.para=para;
}
@Override
public String call() throws Exception {
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(para);
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
return sb.toString();
}
}
main方法
package com.jia.concurrency.future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureMain {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//构造FutureTask
FutureTask<String> future=new FutureTask<>(new RealData("a"));
ExecutorService executor=Executors.newFixedThreadPool(1);
//执行FutureTask/
//在这里开始线程进行RealData的call执行
executor.submit(future);
System.err.println("请求完毕");
try {
//这里依然可以做额外的数据操作.这里使用sleep代替其他业务逻辑的处理
Thread.sleep(2000);
} catch (InterruptedException e) {
}
//此时call()方法没有执行完成,则依然会等待
System.err.println("数据="+future.get());
// while (future.isDone()) {
//
//
// }
//其他一些常用的方法
//future.cancel(boolean mayInterruptIfRunning)
//future.isCancelled();
//future.isDone();
}
}