import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo_05 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程 完成求两个整数的和
SonRunnable sr = new SonRunnable(10, 20);
Thread t = new Thread(sr);
t.start();
/*创建线程的方式三
* 1.实现Callable接口 同时定义call方法的返回值类型
2.重写call方法 线程要运行的代码
3.创建FutureTask对象 将Callable接口实现类进行转换 获取结果
4.创建Thread类 传入FutureTask对象
5.调用FutureTask的get方法 获取call方法的返回值
Callable 产生结果
FutureTask 获取结果
* */
SonCallable sc = new SonCallable(20, 30);
FutureTask<Integer> ft = new FutureTask<>(sc);//FutureTask 是Runnable的实现类
Thread t2 = new Thread(ft);
t2.start();
//获取call方法的返回值 调用FutureTask的get方法
Integer i = ft.get();
System.out.println(i);
}
}
class SonCallable implements Callable<Integer>{
private int a;
private int b;
public SonCallable(int a,int b){
this.a = a;
this.b = b;
}
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+":::"+(a+b));
return a + b;
}
}
class SonRunnable implements Runnable{
private int a;
private int b;
public SonRunnable(int a,int b){
this.a = a;
this.b = b;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"求和..."+(a+b));
//return a+b;
//int x = 10/0; 如果run方法中出现异常 只能使用 try...catch 处理
}
}