public class CallableDemo { public static void main(String[] args) throws Exception, ExecutionException { FutureTaskfutureTask = new FutureTask<>(new CallableThread()); new Thread(futureTask,"A").start(); System.out.println(futureTask.get());//会阻塞,等待执行结束 System.out.println(Thread.currentThread().getName()+"线程执行结束!"); } } class CallableThread implements Callable { @Override public String call() throws Exception { // TODO Auto-generated method stub System.out.println("欢迎使用Callable接口"); try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "Call()执行结束"; } }
执行结果:
欢迎使用Callable接口
(等待三秒后,才会打印下面)
Call()执行结束
main线程执行结束
public class CallableDemo { public static void main(String[] args) throws Exception, ExecutionException { FutureTaskfutureTask = new FutureTask<>(new CallableThread()); new Thread(futureTask,"A").start(); //System.out.println(futureTask.get());//会阻塞,等待执行结束 System.out.println(Thread.currentThread().getName()+"线程执行结束!"); System.out.println(futureTask.get()); } } class CallableThread implements Callable { @Override public String call() throws Exception { // TODO Auto-generated method stub System.out.println("欢迎使用Callable接口"); try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "Call()执行结束"; } }
main线程执行结束!
欢迎使用Callable接口
(等待三秒后,执行下面逻辑)
Call()执行结束