java 线程池 以及在mvc中的使用

1.ThreadPoolExecutor的常用参数及方法

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)
corePoolSize 核心线程池的大小,线程池中的数目达到corePoolSize,则会放入缓存队列中
maximumPoolSize 最大线程数
workQueue 阻塞队列,存储等待执行的任务,常用的:ArrayBlockingQueue、LinkedBlockingQueue(常用)、Synchronous,排队策略
handler 拒绝处理策略,AbortPolicy丢弃任务,抛出RejectedExecutionException异常  DiscarPolicy抛弃任务,不抛出异常
                     DiscardOldestPolicy 丢弃队列最前面的任务,依次重复  CallersRunsPolicy由调用线程处理

execute()向线程池中提交一个任务
submit()也是用来想线程池中提交一个任务,但可以返回执行的结果,利用了Future
shutdown()  shutdownNow() 关闭线程池

2.线程池的具体实现原理

ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,200,TIMEUNIT.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5));
executor.execute(runnable);

但是java中,我们常习惯于使用Executors类来创建线程池,
Executors.newCacheThreadPool();//缓冲池大小为Integer.MAX_VALUE SynchronousQueue
Executors.newSingleThreaPool();//容量为1 LinkedBlockingQueue core和maximum 值都是1
Executors.newFixedThreadPool(int);//创建固定容量的缓冲池 LinkedBlockingQueue core和maximum    
   值是相等的

3.合理配置线程池的大小

CPU密集型任务,可以设置为N(cpu)+1
IO密集型任务,设置为2*N(cpu)

4.java mvc 线程池的具体使用(带返回值)

4.1线程池类

public class AsyncTask {
    private static ExecutorService threadpool = Executors.newFixedThreadPool(10);//newCachedThreadPool();
    @PreDestroy//销毁之前调用
    public static void destroyExecutor(){
        threadpool.shutdown();
    }

    public static void addThread(FutureTask<String> callable){
        threadpool.execute(callable);
    }
}
4.2 Controller接收到请求
   @RequestMapping("/test")
   @ResponseBody
   public String test(String param){
    String result = "";
    try {
           Callable callable = ()-> {//lambda方式创建callable
               String res = testService.test(param);
               TimeUnit.MILLISECONDS.sleep(100);
               return res;
           };

           FutureTask<String> futureTask = new FutureTask<String>(callable);
           AsyncTask.addThread(futureTask);

           result = futureTask.get();//获取返回值

       }catch (Exception e){ 
           logger.info("test exception");
       }

    return result;
   }
 

猜你喜欢

转载自blog.csdn.net/bighacker/article/details/84848356
今日推荐