全國(guó)咨詢(xún)/投訴熱線(xiàn):400-618-4000

首頁(yè)常見(jiàn)問(wèn)題正文

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

更新時(shí)間:2023-03-27 來(lái)源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

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

  Runnable接口只有一個(gè)無(wú)返回值的run() 方法。它用于定義一個(gè)要在單獨(dú)線(xiàn)程中執(zhí)行的任務(wù)。當(dāng)線(xiàn)程執(zhí)行 run()方法時(shí),它將運(yùn)行任務(wù),但不會(huì)返回任何結(jié)果。因此, Runnable接口更適合用于不需要返回結(jié)果的簡(jiǎn)單任務(wù)。

  Callable接口也是用于定義可以在單獨(dú)線(xiàn)程中執(zhí)行的任務(wù),但是它具有不同的方法簽名。它的call()方法可以返回一個(gè)值,并且可以?huà)伋霎惓!R虼耍?Callable接口更適合需要返回結(jié)果或可能拋出異常的任務(wù)。

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

  下面是一個(gè)簡(jiǎn)單的代碼演示,展示如何使用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();
    }
}

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

分享到:
在線(xiàn)咨詢(xún) 我要報(bào)名
和我們?cè)诰€(xiàn)交談!