Skip to content

Commit 990b0b4

Browse files
committed
第四周作业2:使用循环阻塞主线程直到拿到结果
1 parent 732a43f commit 990b0b4

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package java0.conc0303;
22

3-
import java.util.concurrent.CompletableFuture;
3+
import java.util.concurrent.atomic.AtomicReference;
44

55
/**
66
* 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
@@ -27,12 +27,17 @@ public static void main(String[] args) throws Exception {
2727
// });
2828
// executorService.shutdown();
2929
// countDownLatch.await();
30-
int result = CompletableFuture.supplyAsync(()-> sum()).join();
30+
//int result = CompletableFuture.supplyAsync(()-> sum()).join();
3131

3232
//int result = sum(); //这是得到的返回值
3333
//int result = future.get();
34+
AtomicReference<Integer> result = new AtomicReference<>();
35+
new Thread(() -> result.set(sum())).start();
3436
// 确保 拿到result 并输出
35-
System.out.println("异步计算结果为:"+result);
37+
while (result.get() == null) {
38+
39+
}
40+
System.out.println("异步计算结果为:"+result.get());
3641

3742
System.out.println("使用时间:" + (System.currentTimeMillis() - start) + " ms");
3843

0 commit comments

Comments
 (0)