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 兄妹拍照祝福语简短的话