领略Java的Future模式(2)

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)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsdjfs.html