天天看點

小知識 - Anonymous new Runnable() can be replaced with lambda more…

來友鍊呀: Roc's Blog

一直在做 Java 後端開發,很少手動的去寫線程了,今天在複習 ThreadPool 的時候,發現了一個提示:

小知識 - Anonymous new Runnable() can be replaced with lambda more…

Anonymous new Runnable() can be replaced with lambda.

匿名的建立 Runnable 可以被 Lambda 替換。那肯定要緊追 Lambda 的步伐呀。

【注】在Java 1.7或更早的jvm中不支援Lambda文法。

特意查了查官方文檔,是以以後就可以這樣風騷的去寫:

threadPoolExecutor.execute(() -> {
       System.out.println(Thread.currentThread().getName());
       try {
           Thread.sleep(2000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
 });
           

不需要 new ,不需要 run 方法,直接寫 run 裡面的代碼,效率嗖嗖的。

是以說那麼 Thread 建立匿名線程的時候,我們也可以這麼寫:

new Thread(() -> {
    System.out.println("Hello!");
    System.out.println("我是一個線程!");
}).start();

// 等同于

new Thread(new Runnable() {
     @Override
     public void run() {
          System.out.println("Hello!");
          System.out.println("我是一個線程!");
     }
}).start();


// 如果 run() 方法裡面隻有一個語句,還可以這樣寫

new Thread( () -> System.out.println("Hello!我是一個線程!") ).start();
           

拓展:

在這裡僅僅是匿名 Runnable 的例子,其實在開發過程中,也會有其他的匿名函數,如:

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10,
                10L, TimeUnit.SECONDS, new LinkedBlockingQueue(100));
// submit 使用
Future<String> future = threadPoolExecutor.submit(new Callable<String>() {
   @Override
   public String call() throws Exception {
       System.out.println("Hello, 老王.");
       return "Success";
   }
});

// 等價于

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10,
                10L, TimeUnit.SECONDS, new LinkedBlockingQueue(100));
// submit 使用
Future<String> future = threadPoolExecutor.submit(() -> {
     System.out.println("Hello, 老王.");
     return "Success";
});
           

當然也可以自己去實作一個匿名函數:

public class TestMain {

    public static void main(String[] args) {
        // 實作了一個回調函數
        new TestMain().testMethod((message) -> {
            System.out.println(message);
        });
    }

    private void testMethod(TestInterface testInterface) {
        testInterface.show("你好!Java!");
    }
}

interface TestInterface {
    //隻有一個方法的時候可以,多個則不能使用 Lambda 文法。
    void show(String message);
}
           

感謝閱讀!!提前祝您新年快樂!!!

小知識 - Anonymous new Runnable() can be replaced with lambda more…