zoukankan      html  css  js  c++  java
  • cocurrent包ExecutorService线程池

    16. 执行器服务 ExecutorService

    java.util.concurrent.ExecutorService 接口表示一个异步执行机制,使我们能够在后台执行任务。因此一个 ExecutorService 很类似于一个线程池。实际上,存在于 java.util.concurrent 包里的 ExecutorService 实现就是一个线程池实现。

    ExecutorService 例子

    以下是一个简单的 ExecutorService 例子:

    [java] view plain copy
     
    1. ExecutorService executorService = Executors.newFixedThreadPool(10);  
    2.   
    3. executorService.execute(new Runnable() {  
    4.     public void run() {  
    5.         System.out.println("Asynchronous task");  
    6.     }  
    7. });  
    8.   
    9. executorService.shutdown();  


    首先使用 newFixedThreadPool() 工厂方法创建一个 ExecutorService。这里创建了一个十个线程执行任务的线程池。
    然后,将一个 Runnable 接口的匿名实现类传递给 execute() 方法。这将导致 ExecutorService 中的某个线程执行该 Runnable。

    ExecutorService 实现

    既然 ExecutorService 是个接口,如果你想用它的话就得去使用它的实现类之一。java.util.concurrent 包提供了 ExecutorService 接口的以下实现类:

    创建一个 ExecutorService

    ExecutorService 的创建依赖于你使用的具体实现。但是你也可以使用 Executors 工厂类来创建 ExecutorService 实例。以下是几个创建 ExecutorService 实例的例子:

    [java] view plain copy
     
    1. ExecutorService executorService1 = Executors.newSingleThreadExecutor();  
    2.   
    3. ExecutorService executorService2 = Executors.newFixedThreadPool(10);  
    4.   
    5. ExecutorService executorService3 = Executors.newScheduledThreadPool(10);  

    ExecutorService 使用

    有几种不同的方式来将任务委托给 ExecutorService 去执行:

    • execute(Runnable)
    • submit(Runnable)
    • submit(Callable)
    • invokeAny(...)
    • invokeAll(...)

    接下来我们挨个看一下这些方法。

    execute(Runnable)

    execute(Runnable) 方法要求一个 java.lang.Runnable 对象,然后对它进行异步执行。以下是使用 ExecutorService 执行一个 Runnable 的示例:

    [java] view plain copy
     
    1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
    2.   
    3. executorService.execute(new Runnable() {  
    4.     public void run() {  
    5.         System.out.println("Asynchronous task");  
    6.     }  
    7. });  
    8.   
    9. executorService.shutdown();  


    没有办法得知被执行的 Runnable 的执行结果。如果有需要的话你得使用一个 Callable(以下将做介绍)。

    submit(Runnable)

    submit(Runnable) 方法也要求一个 Runnable 实现类,但它返回一个 Future 对象。这个 Future 对象可以用来检查 Runnable 是否已经执行完毕。
    以下是 ExecutorService submit() 示例:

    [java] view plain copy
     
    1. Future future = executorService.submit(new Runnable() {  
    2.     public void run() {  
    3.         System.out.println("Asynchronous task");  
    4.     }  
    5. });  
    6.   
    7. future.get();  //returns null if the task has finished correctly.  

    submit(Callable)

    submit(Callable) 方法类似于 submit(Runnable) 方法,除了它所要求的参数类型之外。Callable 实例除了它的 call() 方法能够返回一个结果之外和一个 Runnable 很相像。Runnable.run() 不能够返回一个结果。
    Callable 的结果可以通过 submit(Callable) 方法返回的 Future 对象进行获取。以下是一个 ExecutorService Callable 示例:

    [java] view plain copy
     
    1. Future future = executorService.submit(new Callable(){  
    2.     public Object call() throws Exception {  
    3.         System.out.println("Asynchronous Callable");  
    4.         return "Callable Result";  
    5.     }  
    6. });  
    7.   
    8. System.out.println("future.get() = " + future.get());  


    以上代码输出:
    Asynchronous Callable
    future.get() = Callable Result

    invokeAny()

    invokeAny() 方法要求一系列的 Callable 或者其子接口的实例对象。调用这个方法并不会返回一个 Future,但它返回其中一个 Callable 对象的结果。无法保证返回的是哪个 Callable 的结果 - 只能表明其中一个已执行结束。
    如果其中一个任务执行结束(或者抛了一个异常),其他 Callable 将被取消。
    以下是示例代码:

    [java] view plain copy
     
    1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
    2.   
    3. Set<Callable<String>> callables = new HashSet<Callable<String>>();  
    4.   
    5. callables.add(new Callable<String>() {  
    6.     public String call() throws Exception {  
    7.         return "Task 1";  
    8.     }  
    9. });  
    10. callables.add(new Callable<String>() {  
    11.     public String call() throws Exception {  
    12.         return "Task 2";  
    13.     }  
    14. });  
    15. callables.add(new Callable<String>() {  
    16.     public String call() throws Exception {  
    17.         return "Task 3";  
    18.     }  
    19. });  
    20.   
    21. String result = executorService.invokeAny(callables);  
    22.   
    23. System.out.println("result = " + result);  
    24.   
    25. executorService.shutdown();  


    上述代码将会打印出给定 Callable 集合中的一个的执行结果。我自己试着执行了它几次,结果始终在变。有时是 "Task 1",有时是 "Task 2" 等等。

    invokeAll()

    invokeAll() 方法将调用你在集合中传给 ExecutorService 的所有 Callable 对象。invokeAll() 返回一系列的 Future 对象,通过它们你可以获取每个 Callable 的执行结果。
    记住,一个任务可能会由于一个异常而结束,因此它可能没有 "成功"。无法通过一个 Future 对象来告知我们是两种结束中的哪一种。
    以下是一个代码示例:

    [java] view plain copy
     
    1. ExecutorService executorService = Executors.newSingleThreadExecutor();  
    2.   
    3. Set<Callable<String>> callables = new HashSet<Callable<String>>();  
    4.   
    5. callables.add(new Callable<String>() {  
    6.     public String call() throws Exception {  
    7.         return "Task 1";  
    8.     }  
    9. });  
    10. callables.add(new Callable<String>() {  
    11.     public String call() throws Exception {  
    12.         return "Task 2";  
    13.     }  
    14. });  
    15. callables.add(new Callable<String>() {  
    16.     public String call() throws Exception {  
    17.         return "Task 3";  
    18.     }  
    19. });  
    20.   
    21. List<Future<String>> futures = executorService.invokeAll(callables);  
    22.   
    23. for(Future<String> future : futures){  
    24.     System.out.println("future.get = " + future.get());  
    25. }  
    26.   
    27. executorService.shutdown();  

    ExecutorService 关闭

    使用完 ExecutorService 之后你应该将其关闭,以使其中的线程不再运行。
    比如,如果你的应用是通过一个 main() 方法启动的,之后 main 方法退出了你的应用,如果你的应用有一个活动的 ExexutorService 它将还会保持运行。ExecutorService 里的活动线程阻止了 JVM 的关闭。
    要终止 ExecutorService 里的线程你需要调用 ExecutorService 的 shutdown() 方法。ExecutorService 并不会立即关闭,但它将不再接受新的任务,而且一旦所有线程都完成了当前任务的时候,ExecutorService 将会关闭。在 shutdown() 被调用之前所有提交给 ExecutorService 的任务都被执行。

    如果你想要立即关闭 ExecutorService,你可以调用 shutdownNow() 方法。这样会立即尝试停止所有执行中的任务,并忽略掉那些已提交但尚未开始处理的任务。无法担保执行任务的正确执行。可能它们被停止了,也可能已经执行结束。

    17. 线程池执行者 ThreadPoolExecutor

    java.util.concurrent.ThreadPoolExecutor 是 ExecutorService 接口的一个实现。ThreadPoolExecutor 使用其内部池中的线程执行给定任务(Callable 或者 Runnable)。
    ThreadPoolExecutor 包含的线程池能够包含不同数量的线程。池中线程的数量由以下变量决定:

    • corePoolSize
    • maximumPoolSize

    当一个任务委托给线程池时,如果池中线程数量低于 corePoolSize,一个新的线程将被创建,即使池中可能尚有空闲线程。
    如果内部任务队列已满,而且有至少 corePoolSize 正在运行,但是运行线程的数量低于 maximumPoolSize,一个新的线程将被创建去执行该任务。
    ThreadPoolExecutor 图解:

    thread-pool-executor
    一个 ThreadPoolExecutor

    创建一个 ThreadPoolExecutor

    ThreadPoolExecutor 有若干个可用构造子。比如:

    [java] view plain copy
     
    1. int  corePoolSize  =    5;  
    2. int  maxPoolSize   =   10;  
    3. long keepAliveTime = 5000;  
    4.   
    5. ExecutorService threadPoolExecutor =  
    6.         new ThreadPoolExecutor(  
    7.                 corePoolSize,  
    8.                 maxPoolSize,  
    9.                 keepAliveTime,  
    10.                 TimeUnit.MILLISECONDS,  
    11.                 new LinkedBlockingQueue<Runnable>()  
    12.                 );  

    但是,除非你确实需要显式为 ThreadPoolExecutor 定义所有参数,使用 java.util.concurrent.Executors 类中的工厂方法之一会更加方便,正如  ExecutorService 小节所述。 

    18.  定时执行者服务 ScheduledExecutorService

    java.util.concurrent.ScheduledExecutorService 是一个 ExecutorService, 它能够将任务延后执行,或者间隔固定时间多次执行。 任务由一个工作者线程异步执行,而不是由提交任务给 ScheduledExecutorService 的那个线程执行。

    ScheduledExecutorService 例子

    以下是一个简单的 ScheduledExecutorService 示例:

    [java] view plain copy
     
    1. ScheduledExecutorService scheduledExecutorService =  
    2.         Executors.newScheduledThreadPool(5);  
    3.   
    4. ScheduledFuture scheduledFuture =  
    5.     scheduledExecutorService.schedule(new Callable() {  
    6.         public Object call() throws Exception {  
    7.             System.out.println("Executed!");  
    8.             return "Called!";  
    9.         }  
    10.     },  
    11.     5,  
    12.     TimeUnit.SECONDS);  


    首先一个内置 5 个线程的 ScheduledExecutorService 被创建。之后一个 Callable 接口的匿名类示例被创建然后传递给 schedule() 方法。后边的俩参数定义了 Callable 将在 5 秒钟之后被执行。

    ScheduledExecutorService 实现

    既然 ScheduledExecutorService 是一个接口,你要用它的话就得使用 java.util.concurrent 包里对它的某个实现类。ScheduledExecutorService 具有以下实现类:

    • ScheduledThreadPoolExecutor

    创建一个 ScheduledExecutorService

    如何创建一个 ScheduledExecutorService 取决于你采用的它的实现类。但是你也可以使用 Executors 工厂类来创建一个 ScheduledExecutorService 实例。比如:

    [java] view plain copy
     
    1. ScheduledExecutorService scheduledExecutorService =  
    2.   
    3.         Executors.newScheduledThreadPool(5);  

    ScheduledExecutorService 使用

    一旦你创建了一个 ScheduledExecutorService,你可以通过调用它的以下方法:

    • schedule (Callable task, long delay, TimeUnit timeunit)
    • schedule (Runnable task, long delay, TimeUnit timeunit)
    • scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)
    • scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

    下面我们就简单看一下这些方法。

    schedule (Callable task, long delay, TimeUnit timeunit)

    这个方法计划指定的 Callable 在给定的延迟之后执行。
    这个方法返回一个 ScheduledFuture,通过它你可以在它被执行之前对它进行取消,或者在它执行之后获取结果。
    以下是一个示例:

    [java] view plain copy
     
    1. ScheduledExecutorService scheduledExecutorService =  
    2.         Executors.newScheduledThreadPool(5);  
    3.   
    4. ScheduledFuture scheduledFuture =  
    5.     scheduledExecutorService.schedule(new Callable() {  
    6.         public Object call() throws Exception {  
    7.             System.out.println("Executed!");  
    8.             return "Called!";  
    9.         }  
    10.     },  
    11.     5,  
    12.     TimeUnit.SECONDS);  
    13.   
    14. System.out.println("result = " + scheduledFuture.get());  
    15.   
    16. scheduledExecutorService.shutdown();  


    示例输出结果:
    Executed!
    result = Called!

    schedule (Runnable task, long delay, TimeUnit timeunit)

    除了 Runnable 无法返回一个结果之外,这一方法工作起来就像以一个 Callable 作为一个参数的那个版本的方法一样,因此 ScheduledFuture.get() 在任务执行结束之后返回 null。

    scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)

    这一方法规划一个任务将被定期执行。该任务将会在首个 initialDelay 之后得到执行,然后每个 period 时间之后重复执行。
    如果给定任务的执行抛出了异常,该任务将不再执行。如果没有任何异常的话,这个任务将会持续循环执行到 ScheduledExecutorService 被关闭。
    如果一个任务占用了比计划的时间间隔更长的时候,下一次执行将在当前执行结束执行才开始。计划任务在同一时间不会有多个线程同时执行。

    scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

    除了 period 有不同的解释之外这个方法和 scheduleAtFixedRate() 非常像。
    scheduleAtFixedRate() 方法中,period 被解释为前一个执行的开始和下一个执行的开始之间的间隔时间。
    而在本方法中,period 则被解释为前一个执行的结束和下一个执行的结束之间的间隔。因此这个延迟是执行结束之间的间隔,而不是执行开始之间的间隔。

    ScheduledExecutorService 关闭

    正如 ExecutorService,在你使用结束之后你需要把 ScheduledExecutorService 关闭掉。否则他将导致 JVM 继续运行,即使所有其他线程已经全被关闭。

    你可以使用从 ExecutorService 接口继承来的 shutdown() 或 shutdownNow() 方法将 ScheduledExecutorService 关闭。参见 ExecutorService 关闭部分以获取更多信息。

  • 相关阅读:
    ADO.NET存取数据库数据
    2017-01-03
    re模块
    random模块(随机)
    sys模块
    os模块
    datetime模块
    time模块
    logging模块
    Python函数初识
  • 原文地址:https://www.cnblogs.com/panxuejun/p/8566055.html
Copyright © 2011-2022 走看看