获取多线程的结果

import java.util.concurrent.*;

/**
* 描述:多线程Future
*
* @auther husheng
* @date 2020/5/23 0:46
*/
public class MultithreadingDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();

//线程1
Future<Integer> future1 = executorService.submit(new Callable<Integer>() {
public Integer call() throws Exception {
int a = 10;
int b = 20;
int c = a + b;
return c;
}
});

//线程2
FutureTask<Integer> future2 = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += i;
}
return sum; //45
}
});
executorService.execute(future2); //执行线程2


//主线程获取线程1的结果
try {
Integer result1 = future1.get();//线程1结果
Integer result2 = future2.get(400, TimeUnit.SECONDS);//线程2结果
System.out.println("Result1=" + result1);
System.out.println("Result2=" + result2);
} catch (Exception e) {
e.printStackTrace();
}

}
}



运行结果:
Result1=30
Result2=45


猜你喜欢

转载自www.cnblogs.com/husheng1987hs/p/12940713.html