美文网首页
java 匿名内部类及 lambda 写法【纯记录使用】

java 匿名内部类及 lambda 写法【纯记录使用】

作者: ithankzc | 来源:发表于2021-12-14 23:15 被阅读0次

    展示一段最近学习的代码

            ThreadPoolExecutor pool = new ThreadPoolExecutor(
                    1,
                    2,
                    1000,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(2),
                    Executors.defaultThreadFactory(),
                    new RejectedExecutionHandler() {
                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                            // TODO
                        }
                    }
    

    从 node 接触 kotlin, 再到 java ,总会接触到更多的知识点。

    比如初始化连接池,定义错误处理器的时候,且其他地方也不会用到,这个时候就可以定义匿名内部类

                    new RejectedExecutionHandler() {
                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                            // TODO
                        }
                    }
    

    我们可以看下这个 RejectedExecutionHandler 接口,只定义 rejectedExecution 这个方法

    public interface RejectedExecutionHandler {
    
        /**
         * Method that may be invoked by a {@link ThreadPoolExecutor} when
         * {@link ThreadPoolExecutor#execute execute} cannot accept a
         * task.  This may occur when no more threads or queue slots are
         * available because their bounds would be exceeded, or upon
         * shutdown of the Executor.
         *
         * <p>In the absence of other alternatives, the method may throw
         * an unchecked {@link RejectedExecutionException}, which will be
         * propagated to the caller of {@code execute}.
         *
         * @param r the runnable task requested to be executed
         * @param executor the executor attempting to execute this task
         * @throws RejectedExecutionException if there is no remedy
         */
        void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
    }
    

    在 java 8 后,则可以用更优雅的写法,比如用 lambda 的方式写

            ThreadPoolExecutor pool = new ThreadPoolExecutor(1,
                    2,
                    1000,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(2),
                    Executors.defaultThreadFactory(),
                    (r, executor) -> {
                        // TODO
                    }
            );
    

    但用 lambda 的前提是 该接口定义了一个方法,java 编译系统才能正常的推导,多方法就用不了啦。

    相关文章

      网友评论

          本文标题:java 匿名内部类及 lambda 写法【纯记录使用】

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