更新时间:2023-03-27 来源:黑马程序员 浏览量:

Runnable和Callable都是Java中用来实现多线程的接口。它们都表示可以在一个单独的线程中执行的代码块。然而,它们之间有一些区别。
Runnable接口只有一个无返回值的run() 方法。它用于定义一个要在单独线程中执行的任务。当线程执行 run()方法时,它将运行任务,但不会返回任何结果。因此, Runnable接口更适合用于不需要返回结果的简单任务。
Callable接口也是用于定义可以在单独线程中执行的任务,但是它具有不同的方法签名。它的call()方法可以返回一个值,并且可以抛出异常。因此, Callable接口更适合需要返回结果或可能抛出异常的任务。

下面是一个简单的代码演示,展示如何使用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();
}
}在这个例子中,我们创建了一个单线程的线程池,并分别定义了一个Runnable和一个 Callable任务。我们将这些任务提交到线程池中,并使用Future对象来跟踪任务的执行和返回值。最后,我们等待任务完成并打印它们的结果。在任务完成后,我们关闭线程池。注意到,task1并不返回任何值,因此我们在等待结果时只能得到null。相反,task2返回一个整数值,因此我们可以通过future2.get()得到这个值。
毕业16个工作日,平均薪资13180元,就业率100%,广州黑马AI智能应用开发(Java)学科20250529班
2026-03-06毕业32个工作日,平均薪资11147元,就业率95%,广州黑马AI智能应用开发(Java)学科20250326班
2026-03-05黑马程序员2025全国就业数据发布:全学科平均就业率92.07%,AI开发类就业平均薪资达11869.67元。
2026-03-05黑马全国校区齐开班!场面太太太壮观了!
2026-03-03AI智能应用开发课程紧贴企业刚需,全程高效学习,直达中高级软件开发水平
2026-02-28风口正劲!黑马程序员又一AI智能应用开发班毕业当天100%就业!
2026-02-27