从3个简单的问题了解线程池的使用

目录

1.为什么最大线程数没满,但是runnable无法立即执行或者无法执行?

2.为什么禁止使用 Executors创建线程池?

3.不能使用Executors创建线程池,那该怎么使用线程池?


前言:

文章,一为温故而知新,二若是可以帮助到别人,也是我的荣幸。

因本人能力有限,若有错误之处,麻烦指出。如果觉得有可取之处,麻烦点赞支持一下。 😊

1.为什么最大线程数没满,但是runnable无法立即执行或者无法执行?

现象:明明我的线程池最大线程数是10,然后其他5个线程都在wait如何知道那5个线程是在wait,看调式技巧,这个时候往线程池中仍一个runnable,线程池却不会创建一个新的线程来执行这个runnable。线程池参数如下所示:

ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger mCount = new AtomicInteger(1);

                @Override
                public Thread newThread(@NotNull Runnable r) {
                    Thread t = new Thread(r, "lightWeight_" + (mCount.getAndIncrement()));
                    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            e.printStackTrace();
                        }
                    });
                    return t;
                }
            });
        }

 解析:上述代码中,线程池的核心线程池为5,最大线程池为10。

当核心线程数满的时候,再仍进去一个runnable,那么此时,线程池不会创建一个新的线程去执行这个runnable,而是把这个runnable添加到linkedBlockingQueue这个队列。

要是前面的5个线程一直不执行完的话,那个后续添加的runnable会继续添加到这个队列中,直到这个队列满了,才会去创建非核心线程去执行后面添加进来的runnable。

而上述代码中的linkedBlockingQueue是一个无界的队列,于是要是前面的5个线程一直不执行完的话,后续添加的runnable都会继续到添加到这个队列中,这样就会造成内存一直增大,最后导致oom。

如果需要在核心线程满,而最大线程数没满的时候,仍runnable进去立即执行,则应该队列使用SynchronousQueue。

 

2.为什么禁止使用 Executors创建线程池?

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }


 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

上述两个线程池的队列使用的是linkedBlockingQueue,它是一个无界的队列,然后如果核心线程要是一直不执行完得话,就会一直往队列里面添加runnable,最终导致oom。

 

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }



public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }

上述两个线程池的非核心数线程数为int的最大值,如果一直往线程池中添加runnable的话,会导致一直创建新的线程,最终也会导致oom。

 

3.不能使用Executors创建线程池,那该怎么创建线程池?

一开始看见有人有这个问题的时候,我不厚道的笑了,Executors不能用,你可以用ThreadPoolExecutor创建哎。

corePoolSize 核心线程池数的话一般都是设置为Cpu核数,或者设置为核数加1(这有种说法,看是IO密集型还是cpu密集型再来设置核数)

maximumPoolSize 非核心线程池数的话,客户端不需要太大,20的数值参考的AsyncTask

keepAliveTime  存活时间的话,有核心线程数的线程池,建议为0s,没有核心线程数的话,建议60s,单纯理论建议

队列:看需求吧,个人比较喜欢用SynchronousQueue

LinkedBlockingQueue:无界的队列

SynchronousQueue:直接提交的队列

DelayedWorkQueue:等待队列

ThreadFactory 创建线程一定要记得给名字,不然后期优化的时候,你根本都不知道这些线程是哪里来的。

将线程池分为轻量级和重量级的目的是,不想让重量级线程占据轻量级线程池中的核心线程,从而导致频繁的创建线程。这个也看使用场景。

public class ThreadPoolManager {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int LIGHT_KEEP_ALIVE = 1;
    private static final int HEARY_KEEP_ALIVE = 60;
    private static final int MAXIMUM_POOL_SIZE = 20;
    private volatile static ThreadPoolManager instance;
    /**
     * 轻量级线程池,处理一些耗时较少的操作和需要迅速反馈到UI界面的操作
     */
    private ThreadPoolExecutor mLightWeightPool;
    /**
     * 重量级线程池,处理一些耗时较多的操作
     */
    private ThreadPoolExecutor mHeavyWeightPool;

    public static ThreadPoolManager getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolManager.class) {
                if (instance == null) {
                    instance = new ThreadPoolManager();
                }
            }
        }
        return instance;
    }

    private ThreadPoolManager() {

    }

    /**
     * 配置:
     * 核心线程数为CPU的核数+1
     * 等待队列为20
     * 回收时间设置为1S
     * 日常的轻量级的操作
     */
    public ThreadPoolExecutor getLightWeightPool() {
        if (mLightWeightPool == null) {
            mLightWeightPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, LIGHT_KEEP_ALIVE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger mCount = new AtomicInteger(1);

                @Override
                public Thread newThread(@NotNull Runnable r) {
                    Thread t = new Thread(r, "lightWeight_" + (mCount.getAndIncrement()));
                    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            e.printStackTrace();
                        }
                    });
                    return t;
                }
            });
        }
        return mLightWeightPool;
    }

    /**
     * 核心线程为0
     * 最大线程数20
     * 等待队列为0
     * 非核心线程的回收时间为60S
     * ==》耗时较大的操作
     */
    public ThreadPoolExecutor getHeavyWeightPool() {
        if (mHeavyWeightPool == null) {
            mHeavyWeightPool = new ThreadPoolExecutor(0, MAXIMUM_POOL_SIZE, HEARY_KEEP_ALIVE, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger mCount = new AtomicInteger(1);

                @Override
                public Thread newThread(@NotNull Runnable r) {
                    Thread t = new Thread(r, "heavyWeight_" + (mCount.getAndIncrement()));
                    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            e.printStackTrace();
                        }
                    });
                    return t;
                }
            });
        }
        return mHeavyWeightPool;
    }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值