日常梳理-常用代码

线程池

使用

/**
     *
     * @param core 核心线程数
     * @param max 最大线程数
     * @param timeTolive 线程池维护线程所允许的空闲时间
     * @return
     */
    @Bean("transactionTaskExecutor")
    public ExecutorService createExcutorService(int core,int max,int timeTolive){
        return new ThreadPoolExecutor(core, max, timeTolive, TimeUnit.SECONDS, new SynchronousQueue<>(),
                new ThreadFactory() {
                    private final ThreadGroup group;
                    private final AtomicInteger threadNum = new AtomicInteger(1);
                    private final String namePrefix;
                    {
                        SecurityManager securityManager = System.getSecurityManager();
                        group = (securityManager != null) ? securityManager.getThreadGroup()
                                : Thread.currentThread().getThreadGroup();
                        namePrefix = "xx-xx-Task-";
                    }
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(group,r,namePrefix + threadNum.getAndIncrement(),0);
                        if(thread.isDaemon()){
                            thread.setDaemon(false);
                        }
                        if(thread.getPriority() != Thread.NORM_PRIORITY){//优先级5
                            thread.setPriority(Thread.NORM_PRIORITY);
                        }
                        return thread;
                    }
                },new ThreadPoolExecutor.CallerRunsPolicy());//用调用者所在的线程来执行任务
    }

ThreadPoolExecutor的4种拒绝策略

  • ThreadPoolExecutor.AbortPolicy()

当新任务被线程池拒绝时,会抛出RejectedExecutionException

  • ThreadPoolExecutor.CallerRunsPolicy

当任务被线程池拒绝时,线程池会将被拒绝的任务添加到线程池中正在运行的线程中运行,由此线程去处理该任务

  • ThreadPoolExecutor.DiscardPolicy()

丢弃任务,但是不抛弃异常。当缓冲队列和线程池满时,其它任务将被丢弃。

  • ThreadPoolExecutor.DiscardOldestPolicy()
    当新任务被线程池拒绝时,首先会丢弃缓冲队列最前面的任务,然后将被拒绝的任务添加到末尾。

Future使用

Future 表示一个可能还没有完成的异步任务的结果,通过 get 方法获取执行结果,该方法会阻塞直到任务返回结果。

  • get():获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回
  • get(long timeout, TimeUnit unit):用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null
public class CallableAndFuture {

    public static ExecutorService executorService = new ThreadPoolExecutor(4, 40,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(1024), new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy());


    static class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "异步处理,Callable 返回结果";
        }
    }

    public static void main(String[] args) {
        Future<String> future = executorService.submit(new MyCallable());
        try {
            System.out.println(future.get());
        } catch (Exception e) {
            // nodo
        } finally {
            executorService.shutdown();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值