实现线程的第三种方式:实现Callable接口


	实现线程的第三种方式:实现Callable接口
[编程语言教程]

实现Callable接口(jdk8新特性)
可以获得线程的返回值

*前两种方式没有返回值,因为run方法返回void

创建一个未来任务类对象 Futrue task = new Future(Callable<>);重写call()方法    可以使用匿名内部类方式
task.get()方法获取线程返回结果

get方法执行会导致当前方法阻塞 效率较低

 

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test_13 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "begin");
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
System.out.println(Thread.currentThread().getName() + "start");
Thread.sleep(1000 * 5);
int a = 100;
int b = 200;
System.out.println(Thread.currentThread().getName() + "over");
return a + b;
}
});
Thread thread = new Thread(task);
thread.start();
try {
System.out.println(task.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "end");
}
}

实现线程的第三种方式:实现Callable接口

原文地址:https://www.cnblogs.com/llcy/p/13468394.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 实现线程的第三种方式:实现Callable接口