File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments