Skip to content

Commit 2284d32

Browse files
committed
第四周作业2:方法一 使用future#get拿到异步任务的返回值
1 parent d155283 commit 2284d32

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

03concurrency/0301/src/main/java/java0/conc0303/Homework03.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package java0.conc0303;
22

3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.Future;
6+
37
/**
48
* 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
59
* 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
@@ -9,14 +13,17 @@
913
*/
1014
public class Homework03 {
1115

12-
public static void main(String[] args) {
16+
public static void main(String[] args) throws Exception {
1317

1418
long start=System.currentTimeMillis();
1519
// 在这里创建一个线程或线程池,
1620
// 异步执行 下面方法
17-
18-
int result = sum(); //这是得到的返回值
19-
21+
ExecutorService executorService = Executors.newCachedThreadPool();
22+
Future<Integer> future = executorService.submit(() -> sum());
23+
executorService.shutdown();
24+
25+
//int result = sum(); //这是得到的返回值
26+
int result = future.get();
2027
// 确保 拿到result 并输出
2128
System.out.println("异步计算结果为:"+result);
2229

0 commit comments

Comments
 (0)