要实现有返回值的多线程,具体代码如下:
package thread; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; public class App { public static class MySum implements Callable<Integer> { @Override
public Integer call() throws Exception {
System.out.println("准备计算");
Thread.sleep(2000);
int sum = 0;
for (int i = 0; i < 5000; i++) {
sum += i;
}
System.out.println("计算结果:" + sum);
return sum;
} } public static void main(String[] args) throws InterruptedException, ExecutionException {
MySum mysum=new MySum();
FutureTask<Integer> futureTask=new FutureTask<>(mysum);
new Thread(futureTask).start();
System.out.println("主线程的最终结果是:"+futureTask.get());
} }
1.FutureTask实现了接口Runnable,所以可以传入到线程中执行
2.futureTask.get()是一个阻塞方法
3.Callable<Integer>中的Integer表示返回的数据类型