Java中Runnable和Callable接口的区别
Runnable和Callable都是函数式接口。实现这些接口的类旨在由另一个线程执行。
线程可以使用Runnable启动,并且有两种启动新线程的方法:一种是通过继承Thread类,另一种是实现Runnable接口。
Thread类没有Callable的构造函数,因此我们应该使用ExecutorService类来执行线程。
| 序号 | 关键 | Runnable | Callable |
|---|---|---|---|
| 1 | 包 | 它属于Java.lang | 它属于java.util.concurrent |
| 2 | 线程创建 | 我们可以通过传递Runnable作为参数来创建线程。 | 我们不能通过传递Callable作为参数来创建线程 |
| 3 | 返回值 | Runnable不返回任何内容 | Callable可以返回结果 |
| 4. | 方法 | 它具有run()方法 | 它具有call()方法 |
| 5 | 批量执行 | 它不能用于任务的批量执行 | 它可以通过调用invokeAll()用于任务的批量执行。 |
Runnable示例
public class RunnableExample implements Runnable {
public void run() {
System.out.println("Hello from a Runnable!");
}
public static void main(String args[]) {
(new Thread(new RunnableExample())).start();
}
}Callable示例
public class Main {
public static void main(String args[]) throws InterruptedException, ExecutionException {
ExecutorService services = Executors.newSingleThreadExecutor();
Future<?> future = services.submit(new Task());
System.out.println("In Future Object" + future.get());
}
}
import java.util.concurrent.Callable;
public class Task implements Callable {
@Override
public String call() throws Exception {
System.out.println("In call");
String name = "test";
return name;
}
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP