public static void main(String[] args)throws Exception{
Callable c1 = new Callable() {
@Override
public Object call() throws Exception {
System.out.println("task1 start");
Thread.sleep(2000);
System.out.println("task1 end");
return "完成 任务1 ";
}
};
FutureTask<String> futureTask = new FutureTask<String>(c1);
new Thread(futureTask).start();
Callable c2= new Callable() {
@Override
public Object call() throws Exception {
System.out.println("task2 start");
Thread.sleep(3000);
System.out.println("task2 end");
return "完成 任务2";
}
};
FutureTask futureTask2 = new FutureTask(c2);
new Thread(futureTask2).start();
System.out.println(futureTask.get());
System.out.println(futureTask2.get());
}
运行结果:
task1 start
task2 start
task1 end
完成 任务1
task2 end
完成 任务2
可以看到task1和task2是同时运行的,task2不用等待task1完成后才执行,但是又能确保 先用task1的结果,后用task2的结果。
利用线程池来执行:
//声明固定线程数为5的线程池
static ExecutorService mService = Executors.newFixedThreadPool(5);
/**
* future模式 Future
*/
public static void testFuture1() throws ExecutionException, InterruptedException {
Future<String> future = mService.submit(()->{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "有返回值 运行结束";
});
System.out.println("future is Down1:"+future.isDone());
System.out.println(future.get());
System.out.println("future is Down2:"+future.isDone());
}
/**
* FutureTask
*/
public static void testFuture2() throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(()->{
Thread.sleep(3000);
return "运行成功";
});
mService.execute(futureTask);
System.out.println("futureTask is Down1:"+futureTask.isDone());
System.out.println(futureTask.get());
System.out.println("futureTask is Down2:"+futureTask.isDone());
}
上诉用线程池执行了两种方式写的Future模式