实现线程的第三种方式:实现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");
}
}
posted @ 2020-08-10 10:38  javase-->  阅读(171)  评论(0)    收藏  举报