Skip to content

Commit cca404b

Browse files
author
tanshuai
committed
补交作业
1 parent 3e4e2d2 commit cca404b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
386 KB
Binary file not shown.

Week_04/周四/HomeWork.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package week04;
2+
3+
import java.util.concurrent.*;
4+
5+
/**
6+
* 思考有多少种方式,在 main 函数启动一个新线程,
7+
* 运行一个方法,拿到这个方法的返回值后,退出主线程?
8+
*/
9+
public class HomeWork {
10+
11+
public static void main(String[] args) throws ExecutionException, InterruptedException {
12+
int result = 0;
13+
result = method1();
14+
System.out.println(result);
15+
result = method2();
16+
System.out.println(result);
17+
}
18+
19+
private static int sum() {
20+
return fibo(36);
21+
}
22+
23+
private static int fibo(int a) {
24+
if ( a < 2)
25+
return 1;
26+
return fibo(a-1) + fibo(a-2);
27+
}
28+
29+
public static int method1() throws ExecutionException, InterruptedException {
30+
// 创建线程池
31+
ExecutorService executorService = Executors.newFixedThreadPool(1);
32+
// 获取结果
33+
Future<Integer> future = executorService.submit(new Callable<Integer>() {
34+
@Override
35+
public Integer call() throws Exception {
36+
return HomeWork.sum();
37+
}
38+
});
39+
executorService.shutdown();
40+
return future.get();
41+
}
42+
43+
public static int method2() throws ExecutionException, InterruptedException {
44+
FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
45+
@Override
46+
public Integer call() throws Exception {
47+
return HomeWork.sum();
48+
}
49+
});
50+
new Thread(futureTask).start();
51+
return futureTask.get();
52+
}
53+
}

0 commit comments

Comments
 (0)