
Future类中重要方法包括get()和cancel()。
1、get()获取数据对象,如果数据没有加载,就会阻塞直到取到数据,而 cancel()是取消数据加载。
2、另外一个get(timeout)操作,表示如果在timeout时间内没有取到就失败返回,而不再阻塞。
3、监听程序,并不会停止,可以根据业务需求判断是否需要中断程序;如System.exit(0);
final ExecutorService exec = Executors.newFixedThreadPool(1); Callablecall = new Callable () { public String call() throws Exception { // 业务代码块 return test(); } }; try { Future future = exec.submit(call); String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为1 秒 return obj; } catch (TimeoutException ex) { System.out.println("处理超时啦...."); System.exit(0); } catch (Exception e) { System.out.println("处理失败."); e.printStackTrace(); } exec.shutdown(); // 关闭线程池