zoukankan      html  css  js  c++  java
  • Effective Java 68 Prefer executors and tasks to threads

    Principle

    The general mechanism for executing tasks is the executor service. If you think in terms of tasks and let an executor service execute them for you, you gain great flexibility in terms of selecting appropriate execution policies. In essence, the Executor Framework does for execution what the Collections Framework did for aggregation.

    Exceutor Framework is a flexible interface-based task execution facility.

    Creating work queue with Executor

    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(runnable);

    Here is how to tell the executor to terminate gracefully (if you fail to do this, it is likely that your VM will not exit):

    executor.shutdown();

    Usage of executor service

    Usage

    Utility

    Wait for a particular task to complete.

    "background thread SetObserver"

    Wait for any or all of a collection of tasks to complete.

    invokeAny or invokeAll methods

    Wait for the executor service's graceful termination to complete.

    awaitTermination method

    Retrive the results of tasks one by one as they complete.

    ExecutorCompletionService

    Control every aspect of a thread pool's operation

    ThreadPoolExecutor class

    Small program or lightly loaded server (submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. )

    Executors.newCachedThreadPool

    Heavily loaded production server

    Executors.newFixedThreadPool

    ThreadPoolExecutor

       

    Thread pool (Fixed or variable service number of threads) .

       

    Task - The key abstraction is the unit of work.

    Task category

    return value

    Runnable

    N

    callable

    Y

       

      

    Multithread

    Time accuracy for long running tasks

    Grace recover on uncaught exception

    java.util.Timer

    N

    N

    N

    ScheduledThreadPoolExecutor

    Y

    Y

    Y

       

       

  • 相关阅读:
    2014上半年-学习目录
    c++中智能输出文件
    如何在微博侧栏中加入自己的微博[js]
    oracle数据库性能
    Arcgis for Android 空间数据WKT与JSON描述
    echart 折线图、柱状图、饼图、环形图颜色修改
    Echarts横坐标倾斜,顶部显示数字
    解决svn中“工作副本已经锁定”,或者svn清理失败的解决方法
    Oracle 空间查询, 数据类型为 sdo_geometry
    OSS上无法使用字体文件解决方案
  • 原文地址:https://www.cnblogs.com/haokaibo/p/prefer-executors-and-tasks-to-threads.html
Copyright © 2011-2022 走看看