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

展示一段最近学习的代码

        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 编译系统才能正常的推导,多方法就用不了啦。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容