- Callable<String> task = new Callable<String>() {
- @Override
- public String call() throws Exception{
- //执行耗时代码
- Thread.sleep(10000);
- return "success";
- }
- };
- ExecutorService executorService = Executors.newSingleThreadExecutor();
- Future<String> future = executorService.submit(task);
- try {
- //设置超时时间
- String rst = future.get(5,TimeUnit.SECONDS);
- System.out.println(rst);
- } catch (TimeoutException e) {
- System.out.println("执行超时");
- } catch(Exception e){
- System.out.println("获取数据异常," + e.getMessage());
- }finally {
- executorService.shutdown();
- }