首頁常見問題正文

說一下runnable和callable有什么區(qū)別?

更新時間:2023-03-27 來源:黑馬程序員 瀏覽量:

IT培訓班

  Runnable和Callable都是Java中用來實現(xiàn)多線程的接口。它們都表示可以在一個單獨的線程中執(zhí)行的代碼塊。然而,它們之間有一些區(qū)別。

  Runnable接口只有一個無返回值的run() 方法。它用于定義一個要在單獨線程中執(zhí)行的任務。當線程執(zhí)行 run()方法時,它將運行任務,但不會返回任何結果。因此, Runnable接口更適合用于不需要返回結果的簡單任務。

  Callable接口也是用于定義可以在單獨線程中執(zhí)行的任務,但是它具有不同的方法簽名。它的call()方法可以返回一個值,并且可以拋出異常。因此, Callable接口更適合需要返回結果或可能拋出異常的任務。

1679886628616_runnable和callable有什么區(qū)別?.jpg

  下面是一個簡單的代碼演示,展示如何使用Runnable和Callable接口。

import java.util.concurrent.*;

public class Example {
    
    public static void main(String[] args) throws Exception {
        
        // Create a thread pool with a single thread
        ExecutorService executor = Executors.newSingleThreadExecutor();
        
        // Define a task using a Runnable
        Runnable task1 = () -> {
            System.out.println("Task 1 is running");
        };
        
        // Define a task using a Callable
        Callable<Integer> task2 = () -> {
            System.out.println("Task 2 is running");
            return 42;
        };
        
        // Submit the tasks to the executor
        Future<?> future1 = executor.submit(task1);
        Future<Integer> future2 = executor.submit(task2);
        
        // Wait for the tasks to complete and print their results
        System.out.println("Result of task 1: " + future1.get()); // Prints "Result of task 1: null"
        System.out.println("Result of task 2: " + future2.get()); // Prints "Result of task 2: 42"
        
        // Shut down the executor
        executor.shutdown();
    }
}

  在這個例子中,我們創(chuàng)建了一個單線程的線程池,并分別定義了一個Runnable和一個 Callable任務。我們將這些任務提交到線程池中,并使用Future對象來跟蹤任務的執(zhí)行和返回值。最后,我們等待任務完成并打印它們的結果。在任務完成后,我們關閉線程池。注意到,task1并不返回任何值,因此我們在等待結果時只能得到null。相反,task2返回一個整數(shù)值,因此我們可以通過future2.get()得到這個值。

分享到:
在線咨詢 我要報名
和我們在線交談!