jianlun

Future类中重要方法包括get()和cancel()。

get()获取数据对象,如果数据没有加载,就会阻塞直到取到数据,而 cancel()是取消数据加载。

另外一个get(timeout)操作,表示如果在timeout时间内没有取到就失败返回,而不再阻塞。  

 

Java 代码示例:

        final ExecutorService exec = Executors.newFixedThreadPool(1);
        Callable<String> call = new Callable<String>() {
            public String call() throws Exception {
                // 放入耗时操作代码块        
                int cash = 300;
                String name = "张三";
                System.out.println(name + "现在有" + cash + "元存款");
                User u = new User(name, cash);
                String[] arr = { "线程A", "线程B", "线程C", "线程D", "线程E", "线程F",
                        "线程G", "线程H", "线程I", "线程J" };
                for (int i = 0; i < 10; i++) {
                    MyThread th = new MyThread(arr[i], u,
                            (int) (Math.random() * 1000 - 500));
                    th.start();
                }
                //耗时代码块结束
                Thread.sleep(1000 * 5);
                return "线程执行完成";
            }
        };
        try {
            Future<String> future = exec.submit(call);
            String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为1 秒
            System.out.println("任务成功返回:" + obj);
        } catch (TimeoutException ex) {
            System.out.println("处理超时啦....");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("处理失败.");
            e.printStackTrace();
        }
        exec.shutdown();  // 关闭线程池    

将耗时的代码块放入标注的地方后,即可满足要求。

分类:

技术点:

相关文章:

  • 2021-08-13
  • 2022-12-23
  • 2022-12-23
  • 2021-05-14
  • 2022-12-23
  • 2021-05-19
  • 2022-12-23
  • 2021-12-30
猜你喜欢
  • 2021-12-19
  • 2021-12-19
  • 2021-12-19
  • 2022-01-12
  • 2022-12-23
  • 2021-12-05
相关资源
相似解决方案