更新时间: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()得到这个值。
1024首播|39岁程序员逆袭记:不被年龄定义,AI浪潮里再迎春天
2025-10-241024程序员节丨10年同行,致敬用代码改变世界的你
2025-10-24【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19