java并发工具类

public interface Executor {
    // 在未来的某个时间执行命令。不处理返回结果
    void execute(@NotNull Runnable command);
}

public interface ExecutorService {
    // 提交一个任务,返回一个Future,通过Future的get方法可获取执行结果
    <T> Future<T> submit(@NotNull Callable<T> task);
    <T> Future<T> submit(@NotNull Runnable<T> task, T result);
}

//获取JVM可用的最大处理器数
Runtime.getRuntime().availableProcessors()

    /**
 * Creates a thread pool that reuses a fixed number of threads
 * operating off a shared unbounded queue.  At any point, at most
 * {@code nThreads} threads will be active processing tasks.
 * If additional tasks are submitted when all threads are active,
 * they will wait in the queue until a thread is available.
 * If any thread terminates due to a failure during execution
 * prior to shutdown, a new one will take its place if needed to
 * execute subsequent tasks.  The threads in the pool will exist
 * until it is explicitly {@link ExecutorService#shutdown shutdown}.
 *
 * @param nThreads the number of threads in the pool
 * @return the newly created thread pool
 * @throws IllegalArgumentException if {@code nThreads <= 0}
 
    创建一个固定线程数量的线程池,操作一个共享的无边界的队列。
    任何时刻,最多会有nThreads数量的线程处理任务。
    当有任务在所有线程都处于忙碌状态时提交,这些任务将会在队列中等待直到
    有可用的线程。
    当有任意的线程由于任务执行失败而终止,一个新的线程将会代替它执行未完成
    的任务,如果有必要的话。池中的线程会一直存在直到线程池被显式关闭。
 *
 /
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

/**
    创建一个按需创建线程的线程池,会重用之前创建的线程如果有的话。
    这种线程池可以显著改善这类项目的性能,即项目执行的大都是短期的
    异步任务。调用execute方法会重用之前创建的线程,如果有的话。如果
    没有可用的线程,会创建一个新的线程并放入池中。闲置60秒的线程会被
    终止并移出线程池。因此,长时间闲置的线程池不会消耗任何的资源。
    如果需要相似的但细节不同的线程池,可以用ThreadPoolExecutor的构造器
    创建。
 * Creates a thread pool that creates new threads as needed, but
 * will reuse previously constructed threads when they are
 * available.  These pools will typically improve the performance
 * of programs that execute many short-lived asynchronous tasks.
 * Calls to {@code execute} will reuse previously constructed
 * threads if available. If no existing thread is available, a new
 * thread will be created and added to the pool. Threads that have
 * not been used for sixty seconds are terminated and removed from
 * the cache. Thus, a pool that remains idle for long enough will
 * not consume any resources. Note that pools with similar
 * properties but different details (for example, timeout parameters)
 * may be created using {@link ThreadPoolExecutor} constructors.
 *
 * @return the newly created thread pool
 */
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial
 * parameters, the default thread factory and the default rejected
 * execution handler.
 *
 * <p>It may be more convenient to use one of the {@link Executors}
 * factory methods instead of this general purpose constructor.
 *
 * @param corePoolSize the number of threads to keep in the pool, even
 *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
        核心线程数量,保留在池中的线程数量,即使这些线程都空闲着,除非
        设置了运行核心线程超时【allowCoreThreadTimeout(true)】
 * @param maximumPoolSize the maximum number of threads to allow in the
 *        pool
            最大线程数量,线程池容许的最大线程数量
 * @param keepAliveTime when the number of threads is greater than
 *        the core, this is the maximum time that excess idle threads
 *        will wait for new tasks before terminating.
        当线程数量大于核心线程数量时,这是超出核心线程数量的线程被终止前
        等待任务的最长时间。
 * @param unit the time unit for the {@code keepAliveTime} argument
 * @param workQueue the queue to use for holding tasks before they are
 *        executed.  This queue will hold only the {@code Runnable}
 *        tasks submitted by the {@code execute} method.
        工作队列。这个队列用来保存那些等待执行的任务。这个队列只保存execute方法
        提交的任务。
        以下情形会抛出非法参数异常:            
 * @throws IllegalArgumentException if one of the following holds:<br>
 *         {@code corePoolSize < 0}<br>
 *         {@code keepAliveTime < 0}<br>
 *         {@code maximumPoolSize <= 0}<br>
 *         {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException if {@code workQueue} is null
 */
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

public interface Future<V>
一个Future表示一个异步运算的结果。它提供了方法【isDone()】用来检测计算是否完成,
等待完成,获取计算结果。当运算完成时,只能用get方法获取执行结果。
【get()方法会阻塞,直至得到结果。get(timeout, timeUnit)最多等待timeout长的时间,超时
没得到结果会报异常java.util.concurrent.TimeoutException。】
调用cancel方法尝试取消正在执行的任务。【如果任务以及完成,取消尝试会失败】
如果你想用Future实现可取消功能,但是不提供一个有用的结果,你可以声明Future<?>形式的类,
返回null作为顶层任务的结果。

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

  • 22
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值