Java中Runnable和Callable接口之间的区别
可运行和可调用两个功能接口。实现这些接口的类设计为由另一个线程执行。
可以使用Ruunable启动线程,这是启动新线程的两种方法:一种是通过子类化Thread类,另一种是实现Runnable接口。
线程类没有可调用的构造函数,因此我们应使用ExecutorService类来执行线程。
ItbelongstoJava.lang
Wecancreatethreadbypassingrunnableasaparameter.
Ruunabledoesnotreturnanything
Ithasrun()method
Itcan’tbeusedforbulkexecutionoftask
可运行示例
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;
}
}