可运行和可调用两个功能接口。实现这些接口的类设计为由另一个线程执行。
可以使用Ruunable启动线程,这是启动新线程的两种方法:一种是通过子类化Thread类,另一种是实现Runnable接口。
线程类没有可调用的构造函数,因此我们应使用ExecutorService类来执行线程。
| 序号 | 键 | 可运行 | 可召回 |
|---|---|---|---|
| 1个 | 包 | It belongs to Java.lang | 它属于java.util.concurrent |
| 2 | 线程创建 | We can create thread by passing runnable as a parameter. | 我们不能通过传递callable作为参数来创建线程 |
| 3 | 返回类型 | Ruunable does not return anything | 可调用可返回结果 |
| 4。 | 方法 | It has run() method | 它具有call()方法 |
| 5 | 批量执行 | It can’t be used for bulk execution of task | 通过调用invokeAll(),可将其用于批量执行任务。 |
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();
}
}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;
}
}