美文网首页
线程池的线程分配策略

线程池的线程分配策略

作者: 黄靠谱 | 来源:发表于2019-03-11 09:16 被阅读0次
    1. 如果当前线程数不超过coreSize,则新建一个线程,执行新的任务
    2. 如果当前coreSize已经满了,且没有空闲的线程,则会把这个任务丢到阻塞队列当中
    3. 如果阻塞队列也满了(比如ArrayBlockingQueue,或者LinkedBQ等有界队列时),则会启动新的临时线程
    4. 如果所有的线程都满了,且超过maxSize的时候,就会把任务交给饱和策略处理

    下面的Demo中,前面2个任务会丢到coreThread执行,接下来6个任务会存在阻塞队列当中,后面来的2个新任务,会创建maxThread来执行。

    • 如果遍历的次数超过10,那么就会调用饱和策略
    • 如果LinkedBlockingQueue没有设置长度,那么永远也不会创建超过coreSize的线程
        public static void main(String args[]) throws Exception{
            int corePoolSize = 2;
            int maximumPoolSize = 4;
            long keepAliveTime = 10;
            TimeUnit unit = TimeUnit.SECONDS;
            BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(6);
            ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,workQueue);
            
            for(int i=0;i<10;i++){
                Thread th=new Thread(new Runnable(){
    
                    @Override
                    public void run() {
                        System.out.println("i am in"+Thread.currentThread().getName());
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        System.out.println("i am out"+Thread.currentThread().getName());
                    }});
            
                executor.execute(th);
            }
                System.in.read();
        }
    

    相关文章

      网友评论

          本文标题:线程池的线程分配策略

          本文链接:https://www.haomeiwen.com/subject/zyxvpqtx.html