如果我需要一个线程的执行结果 但是我们又不想去等待这个线程我们可以使用Future
在Future任务执行的时候当前线程是不阻塞的 这样我们可以做其他的工作,当完成其他工作后我们再来取这个future执行的结果
import java.util.concurrent.*;
/**
* Created by donar on 15/9/8.
*/
public class FutureTest {
final static long start=System.currentTimeMillis();
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
System.out.println(timeslot(start)+"任务放入线程池~~");
Callable callable =new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);//休息两秒
System.out.println(timeslot(start)+"任务完成咯~~");
return "finished";
}
};
//执行方式一
//Future<String> future=executorService.submit(callable);
//执行方式二
FutureTask<String> future = new FutureTask<String>(callable);
executorService.execute(future);
System.out.println(timeslot(start)+"不等待这个任务");
doSomething();//做其他事情
if(future.isDone()){
System.out.println(timeslot(start)+"任务跑完了 结果为" +future.get());
}else{
System.out.println(timeslot(start)+"任务还没跑完");
}
doSomething();
System.out.println(timeslot(start)+"...");
}
private static void doSomething() throws InterruptedException {
System.out.println(timeslot(start)+"做其他事情ing");
Thread.sleep(1000);
}
public static String timeslot(long start){
return " time-"+ (System.currentTimeMillis()-start)+"ms--";
}
}
执行结果
time-7ms--任务放入线程池~~
time-9ms--不等待这个任务
time-9ms--做其他事情ing
time-1012ms--任务还没跑完
time-1012ms--做其他事情ing
time-2011ms--任务完成咯~~
time-2016ms--...