zoukankan      html  css  js  c++  java
  • java多线程(ExecutorService)

    ExecutorService exec = null;
    List<IbeFlightInfo> ibeFlightInfo = new ArrayList<IbeFlightInfo>();
    TransferVO[] b2gFlights = new TransferVO[]{};
    try {
    exec = Executors.newFixedThreadPool(2);
    Callable IBEcall = new IBEGetFlightThread(request);
    Callable B2Gcall = new B2GGetFlightThread(request.getDepAirport(), request.getArrAirport(),request.getDepDate());

    /*

    submit(Callable)
    方法 submit(Callable) 和方法 submit(Runnable) 比较类似,但是区别则在于它们接收不同的参数类型。Callable 的实例与 Runnable 的实例很类似,但是 Callable 的 call() 方法可以返回壹個结果。方法 Runnable.run() 则不能返回结果。

    Callable 的返回值可以从方法 submit(Callable) 返回的 Future 对象中获取。

    */


    Future<Object> IBEFuture = exec.submit(IBEcall);
    Future<Object> B2GFuture = exec.submit(B2Gcall);
    int second = 0;
    while (!IBEFuture.isDone() && !B2GFuture.isDone()) {
    TimeUnit.MILLISECONDS.sleep(1000);
    second += 1;
    }

    ibeFlightInfo = (List<IbeFlightInfo>) IBEFuture.get();
    b2gFlights = (TransferVO[]) B2GFuture.get();

    System.out.println("共用時(秒):" + second);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {

    /*

    为了关闭在 ExecutorService 中的线程,你需要调用 shutdown() 方法。ExecutorService 并不会马上关闭,而是不再接收新的任务,壹但所有的线程结束执行当前任务,ExecutorServie 才会真的关闭。所有在调用 shutdown() 方法之前提交到 ExecutorService 的任务都会执行。
    如果你希望立即关闭 ExecutorService,你可以调用 shutdownNow() 方法。这個方法会尝试马上关闭所有正在执行的任务,并且跳过所有已经提交但是还没有运行的任务。但是对于正在执行的任务,是否能够成功关闭它是无法保证的,有可能他们真的被关闭掉了,也有可能它会壹直执行到任务结束。这是壹個最好的尝试。

    */


    exec.shutdown();
    }

  • 相关阅读:
    “main cannot be resolved or is not a field”解决方案
    .net学习笔记----有序集合SortedList、SortedList<TKey,TValue>、SortedDictionary<TKey,TValue>
    MVC学习笔记---ModelBinder
    MVC学习笔记---MVC框架执行顺序
    服务器知识----IIS架设问题
    C/C++学习笔记---primer基础知识
    C/C++学习笔记----指针的理解
    C#学习笔记-----C#枚举中的位运算权限分配
    CSS学习笔记----CSS3自定义字体图标
    Clr Via C#读书笔记----基元线程同步构造
  • 原文地址:https://www.cnblogs.com/flord/p/5920910.html
Copyright © 2011-2022 走看看