线程通用

线程池关系

        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new BlockingArrayQueue<>(10));
        ExecutorService executor = Executors.newSingleThreadExecutor();

        ThreadPoolExecutor mqttDataSendThreadPool = new ThreadPoolExecutor(10, 10, 600L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(100), new ThreadPoolExecutor.DiscardPolicy());

拒绝策略

  • ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
  • ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常。
  • ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新提交被拒绝的任务
  • ThreadPoolExecutor.CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务

线程池动态扩展

原理就是在初始化线程的时候,加入了RejectedExecutionHandler ,在拒绝时,会调用此handler,通过这个handler 可以实现线程池动态扩展

ThreadPoolExecutor executors=new ThreadPoolExecutor(1, 2, 19, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

                executor.setCorePoolSize(executor.getPoolSize()*2);
                executor.setMaximumPoolSize(executor.getMaximumPoolSize()*2);
            }
        });

线程future

submit会catch线程的执行异常,用get 方法可以获取异常,

execute 不会catch异常.

 Future future=mqttDataSendThreadPool.submit(()->{
            System.out.println(Integer.parseInt("JIa"));
        });
        try {
            future.get(10,TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mqttDataSendThreadPool.execute(()->{
            System.out.println(Integer.parseInt("JIa"));
        });

https://www.jianshu.com/p/d7d0a32cf028

Callable

callable 可以通过future返回线程执行结果.


评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注