anonymous new Callable() can be replaced with lambda

背景

當我們使用IDEA時,經常出現下圖的灰色警告,看着很不雅,老覺得自己是不是寫的不規範,顯得逼格不夠高。出現如下情況呢,是因爲當前使用的jdk版本有更簡單的表達式可以代替。
在這裏插入圖片描述

問題

代碼如下:

public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        //創建一個Callable,3秒後返回String類型
        Callable myCallable = new Callable() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                System.out.println("call方法執行了");
                return "call方法返回值";
            }
        };
        System.out.println("提交任務之前 " + LocalDateTime.now().toLocalTime());
        Future future = executor.submit(myCallable);
        System.out.println("提交任務之後,獲取結果之前 " + LocalDateTime.now().toLocalTime());
        System.out.println("獲取返回值: " + future.get());
        System.out.println("獲取到結果之後 " + LocalDateTime.now().toLocalTime());
    }

解決方案

既然IDEA都給出了警告提示,相信IDEA這麼強大的工具肯定也是有了解決方案。接下來就讓我們使用神奇的萬能快捷鍵吧

Alt + Enter

優化後:

  public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        //創建一個Callable,3秒後返回String類型
        Callable myCallable = () -> {
            Thread.sleep(3000);
            System.out.println("call方法執行了");
            return "call方法返回值";
        };
        System.out.println("提交任務之前 " + LocalDateTime.now().toLocalTime());
        Future future = executor.submit(myCallable);
        System.out.println("提交任務之後,獲取結果之前 " + LocalDateTime.now().toLocalTime());
        System.out.println("獲取返回值: " + future.get());
        System.out.println("獲取到結果之後 " + LocalDateTime.now().toLocalTime());
    }

結束語

通過以上的問題,充分體現了快捷鍵的重要性,正所謂學會kkj,走遍天下都不怕。當然在技術的不斷進步中,追求技術的完美也是不可或缺的一點。

發佈了18 篇原創文章 · 獲贊 21 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章