Skip to content

Commit d3ed9cc

Browse files
团子❤️熊二团子❤️熊二
authored andcommitted
Merge branch 'main' of github.com:chengfpvoid/JavaCourseCodes into main
2 parents 729d5d6 + b9c3e5a commit d3ed9cc

File tree

1 file changed

+38
-16
lines changed

1 file changed

+38
-16
lines changed
Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,61 @@
11
package java0.conc0303;
22

3+
import java.util.concurrent.atomic.AtomicReference;
4+
35
import java.util.concurrent.CountDownLatch;
46

7+
58
/**
69
* 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
710
* 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
811
* 写出你的方法,越多越好,提交到github。
9-
*
12+
* <p>
1013
* 一个简单的代码参考:
1114
*/
1215
public class Homework03 {
13-
14-
public static void main(String[] args) {
15-
16-
long start=System.currentTimeMillis();
16+
17+
public static void main(String[] args) throws Exception {
18+
19+
long start = System.currentTimeMillis();
1720
// 在这里创建一个线程或线程池,
1821
// 异步执行 下面方法
19-
20-
int result = sum(); //这是得到的返回值
21-
22+
23+
// CountDownLatch countDownLatch = new CountDownLatch(1);
24+
// ExecutorService executorService = Executors.newCachedThreadPool();
25+
26+
// Future<Integer> future = executorService.submit(() -> sum());
27+
// executorService.execute( () -> {
28+
// int result = sum();
29+
// System.out.println("异步计算结果为:"+result);
30+
// countDownLatch.countDown();
31+
// });
32+
// executorService.shutdown();
33+
// countDownLatch.await();
34+
//int result = CompletableFuture.supplyAsync(()-> sum()).join();
35+
36+
//int result = sum(); //这是得到的返回值
37+
//int result = future.get();
38+
AtomicReference<Integer> result = new AtomicReference<>();
39+
new Thread(() -> result.set(sum())).start();
40+
2241
// 确保 拿到result 并输出
23-
System.out.println("异步计算结果为:"+result);
24-
25-
System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms");
26-
42+
while (result.get() == null) {
43+
44+
}
45+
System.out.println("异步计算结果为:"+result.get());
46+
47+
System.out.println("使用时间:" + (System.currentTimeMillis() - start) + " ms");
48+
2749
// 然后退出main线程
2850
}
29-
51+
3052
private static int sum() {
3153
return fibo(36);
3254
}
33-
55+
3456
private static int fibo(int a) {
35-
if ( a < 2)
57+
if (a < 2)
3658
return 1;
37-
return fibo(a-1) + fibo(a-2);
59+
return fibo(a - 1) + fibo(a - 2);
3860
}
3961
}

0 commit comments

Comments
 (0)