java
package test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Main { public static class MyCallable implements Callable<Integer> { public Integer call() throws Exception { Thread.sleep(10000); return 1; } } public static void main(String[] args) { MyCallable callable = new MyCallable(); FutureTask<Integer> task = new FutureTask<Integer>(callable); Thread t = new Thread(task); try { t.start(); System.out.println(task.get()); System.out.println("here"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
当主线程在等待子线程的结果的时候,主线程本身也被阻塞了。如何做到子线程在做任务的时候,主线程去做其他的事情,等到子线程做完以后,再通知主线程去做?别说NIO。NIO是可以的。
get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
get方法会阻塞。知道获取结果为止。