关于java:关于java线程池的创建

44次阅读

共计 3521 个字符,预计需要花费 9 分钟才能阅读完成。


线程池为线程生命周期开销问题和资源有余问题提供了解决方案。通过对多个工作重用线程,线程创立的开销被摊派到了多个工作上。其益处是,因为在申请达到时线程曾经存在,所以无心中也打消了线程创立所带来的提早。这样,就能够立刻为申请服务,使应用程序响应更快。而且,通过适当地调整线程池中的线程数目,也就是当申请的数目超过某个阈值时,就强制其它任何新到的申请始终期待,直到取得一个线程来解决为止,从而能够避免资源有余。

应用 spring 治理线程池的应用


1、创立线程池的配置信息 threads.properties

#### 业务线程池配置 ####
#是否启用自定义线程池。true 时启动,以下参数失效
handler.threads.custom=false
#外围线程数
handler.threads.corePoolSize=20
#最大线程数
handler.threads.maximumPoolSize=1000
#闲暇线程存活工夫,单位秒
handler.threads.keepAliveTime=100
#工作队列大小,为 0 是无限大
handler.threads.workQueue=0

2、创立 线程池 配置,ThreadsPoolConfig.java

package com.hk.core.concurrent;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 线程池 配置
 */
@Component
public class ThreadsPoolConfig {

    /**
     * 是否开启自定义线程池
     */
    @Value("${handler.threads.custom}")
    private boolean custom;
    /**
     * 外围线程数
     */
    @Value("${handler.threads.corePoolSize}")
    private int corePoolSize;
    /**
     * 线程池最大线程数
     */
    @Value("${handler.threads.maximumPoolSize}")
    private int maximumPoolSize;
    /**
     * 闲暇线程存活工夫(对外围线程有效)*/
    @Value("${handler.threads.keepAliveTime}")
    private long keepAliveTime;
    /**
     * 工作队列大小,0 时为无界队列
     */
    @Value("${handler.threads.workQueue}")
    private int workQueue;

    public boolean isCustom() {return custom;}

    public void setCustom(boolean custom) {this.custom = custom;}

    public int getCorePoolSize() {return corePoolSize;}

    public void setCorePoolSize(int corePoolSize) {this.corePoolSize = corePoolSize;}

    public int getMaximumPoolSize() {return maximumPoolSize;}

    public void setMaximumPoolSize(int maximumPoolSize) {this.maximumPoolSize = maximumPoolSize;}

    public long getKeepAliveTime() {return keepAliveTime;}

    public void setKeepAliveTime(long keepAliveTime) {this.keepAliveTime = keepAliveTime;}

    public int getWorkQueue() {return workQueue;}

    public void setWorkQueue(int workQueue) {this.workQueue = workQueue;}
    
}

3、创立 线程池 处理器治理线程 HandlerThreadsPool.java

package com.hk.core.concurrent;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PreDestroy;

/**
 * 线程管理器
 */
public class HandlerThreadsPool {

    public ExecutorService executorService;
    
    public HandlerThreadsPool() {
        // TODO Auto-generated constructor stub
        this.executorService=Executors.newCachedThreadPool();}
    
    public HandlerThreadsPool(ThreadsPoolConfig config) {
        // TODO Auto-generated constructor stub
        if(config.isCustom()){
            BlockingQueue<Runnable> queue=null;
            if(config.getWorkQueue()>0){queue=new LinkedBlockingQueue<Runnable>(config.getWorkQueue()); // 个别应用 LinkedBlockingQueue 队列
            }else{queue=new LinkedBlockingQueue<Runnable>();
            }        // 配置线程池信息
            this.executorService=new ThreadPoolExecutor(config.getCorePoolSize(), 
                    config.getMaximumPoolSize(), 
                    config.getKeepAliveTime(), 
                    TimeUnit.SECONDS, 
                    queue, 
                    new ThreadPoolExecutor.AbortPolicy()// 回绝策略,工作队列满后,新的工作将被抛弃,并抛出异样);
        }else{this.executorService=Executors.newCachedThreadPool();
        }
    }     /*   * 创立线程,对线程处理事件     */
    public void execute(Runnable runnable){executorService.execute(runnable);
    }
    
        
    /*   * 对象销毁时,销毁线程   */
    @PreDestroy
    public void stop() {executorService.shutdown(); 
    }
    
}

4、应用线程池

package com.hk.core.concurrent;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MsgHandler implements Runnable{

    
    @Autowired
    private  ThreadsPoolConfig config;  // 注入 配置
    
    @Override
    public void run() {
       // do 这里 写 解决的逻辑
        System.out.println("创立线程 处理事务....");
    }

    
    @PostConstruct
    public void loadThreadsPool(){
        
        // 初始化 线程池
        HandlerThreadsPool handlerThreadsPool=new HandlerThreadsPool(config); 
        
        // 调用线程池,创立线程。处理事件
        handlerThreadsPool.execute(new MsgHandler());
    }
}

正文完
 0