Fature的作用是异步获取结果,不影响主线程执行,以下是代码
package com.lujiawei.thread;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;public class UserFature implements Callable{ private int age; public UserFature(int age) { this.age = age; } @Override public Integer call() throws Exception { for(int i=0;i<10;i++){ Thread.sleep(1000); age = age + 1; System.out.println("age --> "+age); } return age; } public static void main(String[] args) throws Exception { int age = 10; UserFature userFature = new UserFature(age); FutureTask futureTask = new FutureTask<>(userFature); ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(1); Future f = newFixedThreadPool.submit(futureTask); System.out.println("直接返回"); System.out.println(f.get());//当返回结果的时候f.get()为null System.out.println("age为-->"+futureTask.get()); }}
打印结果为
直接返回age --> 11age --> 12age --> 13age --> 14age --> 15age --> 16age --> 17age --> 18age --> 19age --> 20nullage为-->20