概述
接口java.util.concurrent.Callable也叫并发,它可以满足多线程需要 返回值 和 抛出异常
Callable 主要方法
接口只有一个方法
V call() throws Exception;:线程要执行的代码,可以返回值 和 抛出异常
FutureTask类
参见:https://www.malaoshi.top/show_1EF4sjjkTp5Y.html
例子:
Callable实现类
import java.util.concurrent.Callable;
public class CallableImpl implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <2000 ; i++) {
sum++;
System.out.println(Thread.currentThread().getName()+"-"+i);
}
return sum;
}
}
测试类:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadTestMain3 {
public static void main(String[] args) {
CallableImpl ci = new CallableImpl();
FutureTask<Integer> ft = new FutureTask<Integer>(ci);
Thread t=new Thread(ft);
t.start();
//在主方法中执行for循环
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName()+"-"+i);
}
try {
System.out.println("结果:"+ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
执行结果:
main-214
main-215
Thread-0-0
main-216
Thread-0-1
main-217
。。。。。。。。
结果:2000