public class FutureGet { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor=Executors.newFixedThreadPool(2); //创建一个Callable,三秒返回String类型 Callable callable = new Callable() { @Override public Object call() throws Exception { Thread.sleep(3000); System.out.println("callable方法执行!"); return "callable"; } }; System.out.println("提交任务之前:"+getStringDate()); Future future = executor.submit(callable); System.out.println("提供任务之后,获取结果之前:"+getStringDate()); System.out.println("获取返回值:"+future.get()); System.out.println("获取到结果之后:"+getStringDate()); } public static String getStringDate(){ Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); String dataString = format.format(date); return dataString; } }
通过上面的输出可以看到,在调动submit提交任务之后,主线程本来是继续运行到future.get()的时候就阻塞了,一直等到任务执行完毕,拿到了返回的返回值,主线程才会继续运行;
阻塞性是因为调用了get()方法时,任务没有执行完毕,所以会一直等到任务完成,形成了阻塞;
任务是在调用submit方法时就开始执行了,如果在调用get方法时,任务已经执行完毕,那么就不会造成阻塞;
下面调用方法前先休眠四秒,这时能马上得到返回值:
submit(Runnable task)
因为Runnable是没有返回值,所以如果submit一个Runnable的话,get得到的值肯定为null;
public class SubmitRunnable { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor= Executors.newFixedThreadPool(2); Runnable runnable = new Runnable() { @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }; Future future = executor.submit(runnable); System.out.println("获得返回值:"+future.get()); } }
submit(Runnable task,T result)
虽然传入Runnable不能直接返回内容,但是可以通过submit(Runnable task,T result)传入一个载体,通过这个载体获取返回值;
public class Data { String name; String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
在Runnable的构造方法中传入:
public class MyThreadData implements Runnable { Data data; public MyThreadData(Data data) { this.data = data; } @Override public void run() { try { Thread.sleep(2000); System.out.println("线程执行:"); data.setName("张三"); data.setSex("女"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] arg) throws ExecutionException, InterruptedException { ExecutorService executor= Executors.newFixedThreadPool(2); Data data = new Data(); Future<Data> submit = executor.submit(new MyThreadData(data), data); System.out.println("返回结果:"+submit.get().getName()+",sex:"+submit.get().getSex()); } }
get(long var1,TimeUnit var3)