前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >线程池的创建和使用

线程池的创建和使用

作者头像
IT云清
发布2019-01-22 15:09:49
1.1K0
发布2019-01-22 15:09:49
举报
文章被收录于专栏:IT云清IT云清
几种线程池的创建和使用

目录:

  • 1.newFixedThreadPool固定线程池
  • 2.newSingleThreadExecutor一个线程的线程池
  • 3.newCachedThreadPool缓存线程池
  • 4.ThreadPoolExecutor
  • 5.Future获取返回结果

1.newFixedThreadPool固定线程池

示例:

代码语言:javascript
复制
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

源码:

代码语言:javascript
复制
    /**
     * 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}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

解读一下源码注释:

代码语言:javascript
复制
创建一个线程池,该线程池复用固定数量的线程去操作一个共享的无界队列;
在任何时刻,最多只有nThreads的线程是处于可处理任务的活跃状态。
当所有的线程都处于活跃状态(在处理任务),如果提交了额外的任务,它将会在队列中等待,直到有线程可用。
如果线程在执行期间由于失败而终止,如果需要的话,一个新的线程将会取代它执行后续任务。
线程池中的线程将会一直存在,直到显示的关闭。

这里需要注意,线程的数量是固定的,但是队列大小是无界的(Integer.MAX_VALUE足够大,大到可以任务无界。)

注意这里用的队列:LinkedBlockingQueue,默认队列大小Integer的最大值。

代码语言:javascript
复制
    /**
     * Creates a {@code LinkedBlockingQueue} with a capacity of
     * {@link Integer#MAX_VALUE}.
     */
    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }

代码测试:

代码语言:javascript
复制
package com.java4all.test11;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * Author: yunqing
 * Date: 2018/9/19
 * Description:
 */
@RestController
@RequestMapping(value = "testThread")
public class TestThread {


    /**固定大小的线程池*/
    static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
    
    @RequestMapping(value = "parse",method = RequestMethod.GET)
    public String parse(){
        Future<?> submit = fixedThreadPool.submit(() -> {
            System.out.println("线程名称:" + Thread.currentThread().getName());
        });
        return null;
    }
}

我们设定固定大小为4的线程池,然后用20个并发请求:

代码语言:javascript
复制
线程名称:pool-1-thread-1
线程名称:pool-1-thread-3
线程名称:pool-1-thread-4
线程名称:pool-1-thread-1
线程名称:pool-1-thread-3
线程名称:pool-1-thread-4
线程名称:pool-1-thread-4
线程名称:pool-1-thread-3
线程名称:pool-1-thread-4
线程名称:pool-1-thread-1
线程名称:pool-1-thread-1
线程名称:pool-1-thread-4
线程名称:pool-1-thread-1
线程名称:pool-1-thread-3
线程名称:pool-1-thread-4
线程名称:pool-1-thread-1
线程名称:pool-1-thread-3
线程名称:pool-1-thread-2
线程名称:pool-1-thread-2
线程名称:pool-1-thread-1

由是于队列无界,200 000个也是可以的,但是处理复杂任务时,无界队列可能会让内存爆掉。

2.newSingleThreadExecutor单线程

示例:

代码语言:javascript
复制
static ExecutorService service = Executors.newSingleThreadExecutor();

源码:

代码语言:javascript
复制
    /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

解读一下源码注释:

代码语言:javascript
复制
创建一个线程执行者,它使用单个线程去操作一个无界队列。
(需要注意:如果一个线程由于执行过程中失败导致线程终止,一个新的线程将会取代他,如果需要执行后续任务)

这里使用的队列,也是LinkedBlockingQueue,需要注意。

3.newCachedThreadPool缓存线程池

示例

代码语言:javascript
复制
static ExecutorService service1 = Executors.newCachedThreadPool();

源码:

代码语言:javascript
复制
    /**
     * 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>());
    }

源码解读:

代码语言:javascript
复制

这里,使用的是异步队列SynchronousQueue,而且是非公平的。

查看下源码:

代码语言:javascript
复制
    /**
     * Creates a {@code SynchronousQueue} with nonfair access policy.
     */
    public SynchronousQueue() {
        this(false);
    }
代码语言:javascript
复制
    /**
     * Creates a {@code SynchronousQueue} with the specified fairness policy.
     *
     * @param fair if true, waiting threads contend in FIFO order for
     *        access; otherwise the order is unspecified.
     如果为真,等待线程按照FIFO顺序,否则,顺序是不确定的。
     */
    public SynchronousQueue(boolean fair) {
        transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
    }

测试一下:

代码语言:javascript
复制
/**
 * Author: yunqing
 * Date: 2018/9/19
 * Description:
 */
@RestController
@RequestMapping(value = "testThread")
public class TestThread {


    /***/
    static ExecutorService service1 = Executors.newCachedThreadPool();
    @RequestMapping(value = "parse",method = RequestMethod.GET)
    public String parse(){
        Future<?> submit = service1.submit(() -> {
            System.out.println("线程名称:" + Thread.currentThread().getName());
        });
        return null;
    }
}

20个并发请求:

代码语言:javascript
复制
线程名称:pool-1-thread-13
线程名称:pool-1-thread-15
线程名称:pool-1-thread-13
线程名称:pool-1-thread-2
线程名称:pool-1-thread-15
线程名称:pool-1-thread-17
线程名称:pool-1-thread-4
线程名称:pool-1-thread-14
线程名称:pool-1-thread-12
线程名称:pool-1-thread-4
线程名称:pool-1-thread-8
线程名称:pool-1-thread-7
线程名称:pool-1-thread-1
线程名称:pool-1-thread-6
线程名称:pool-1-thread-3
线程名称:pool-1-thread-5
线程名称:pool-1-thread-11
线程名称:pool-1-thread-10
线程名称:pool-1-thread-9
线程名称:pool-1-thread-16

注意看,是有线程复用的。

4.ThreadPoolExecutor

4.1这种方式创建线程池,参数很多,由于可以显示指定队列的大小,所以可以合理避免OOM;
4.2拒绝策略
  • AbortPolicy:抛出RejectedExecutionException异常。这种策略时,注意捕获异常。
  • DiscardPolicy:什么也不做,直接忽略
  • DiscardOldestPolicy:丢弃执行队列中最老的任务,尝试为当前提交的任务腾出位置
  • CallerRunsPolicy:直接由提交任务者执行这个任务
代码语言:javascript
复制
/**
 * Author: yunqing
 * Date: 2018/9/19
 * Description:
 */
@RestController
@RequestMapping(value = "testThread")
public class TestThread {


    static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            4,  //corePoolSize:线程核心数量,及时处于idle状态,也不会回收
            10, //maximumPoolSize:线程数的上限
            60, //keepAliveTime:超过这个时间,超过corePoolSize的线程,多余的线程将会被回收
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(300), //任务的排队队列  不显示指定大小,会默认Integer.MAX_VALUE,设置不当容易OOM
            new ThreadPoolExecutor.AbortPolicy()  //拒绝策略
    );
    @RequestMapping(value = "parse",method = RequestMethod.GET)
    public String parse(){
        Future<?> submit = threadPoolExecutor.submit(() -> {
            System.out.println("线程名称:" + Thread.currentThread().getName());
        });
        return "处理完了";
    }
}

5.Future获取返回结果

代码语言:javascript
复制
package com.java4all.test11;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;


/**
 * Author: yunqing
 * Date: 2018/9/19
 * Description:
 */
@RestController
@RequestMapping(value = "testThread")
public class TestThread {


    static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            4,  //corePoolSize:线程核心数量,及时处于idle状态,也不会回收
            10, //maximumPoolSize:线程数的上限
            60, //keepAliveTime:超过这个时间,超过corePoolSize的线程,多余的线程将会被回收
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200), //任务的排队队列  不显示指定大小,会默认Integer.MAX_VALUE,设置不当容易OOM
            new ThreadPoolExecutor.AbortPolicy()  //拒绝策略
    );
    @RequestMapping(value = "parse",method = RequestMethod.GET)
    public String parse(){
        Future<?> future = threadPoolExecutor.submit(() -> {
            Thread.sleep(10000);
            System.out.println("线程名称:" + Thread.currentThread().getName());
            return Thread.currentThread().getName()+":处理完了数据";
        });

        Object o = null;
        try {
            //获取执行结果  如果设置了时间,规定时间内没有处理完,返回结果可能为空
            o = future.get(4,TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        System.out.println(o.toString());
        return "处理完了";
    }
}

future.get()方法,是一个阻塞方法,会等到线程任务执行完了,返回结果;如果设置了时间,会等待到设定的时间,如果超市了还没有计算完成,返回结果可能为null;所以,这里需要注意NPE;

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年09月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 几种线程池的创建和使用
  • 1.newFixedThreadPool固定线程池
  • 2.newSingleThreadExecutor单线程
  • 3.newCachedThreadPool缓存线程池
  • 4.ThreadPoolExecutor
    • 4.1这种方式创建线程池,参数很多,由于可以显示指定队列的大小,所以可以合理避免OOM;
      • 4.2拒绝策略
      • 5.Future获取返回结果
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档