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;
}
}热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短