|
1 | 1 | package java0.conc0303; |
2 | 2 |
|
| 3 | +import java.util.concurrent.CompletableFuture; |
| 4 | + |
3 | 5 | /** |
4 | 6 | * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池, |
5 | 7 | * 异步运行一个方法,拿到这个方法的返回值后,退出主线程? |
6 | 8 | * 写出你的方法,越多越好,提交到github。 |
7 | | - * |
| 9 | + * <p> |
8 | 10 | * 一个简单的代码参考: |
9 | 11 | */ |
10 | 12 | public class Homework03 { |
11 | | - |
| 13 | + |
12 | 14 | public static void main(String[] args) throws Exception { |
13 | | - |
14 | | - long start=System.currentTimeMillis(); |
| 15 | + |
| 16 | + long start = System.currentTimeMillis(); |
15 | 17 | // 在这里创建一个线程或线程池, |
16 | 18 | // 异步执行 下面方法 |
17 | | - // CountDownLatch countDownLatch = new CountDownLatch(1); |
18 | | - // ExecutorService executorService = Executors.newCachedThreadPool(); |
19 | | - |
20 | | - // Future<Integer> future = executorService.submit(() -> sum()); |
21 | | - // executorService.execute( () -> { |
22 | | - // int result = sum(); |
23 | | - // System.out.println("异步计算结果为:"+result); |
24 | | - // countDownLatch.countDown(); |
25 | | - // }); |
26 | | - // executorService.shutdown(); |
27 | | - // countDownLatch.await(); |
28 | | - Thread t1 = new Thread(() -> { |
29 | | - int result = sum(); |
30 | | - System.out.println("异步计算结果为:"+result); |
31 | | - }); |
32 | | - t1.start(); |
33 | | - t1.join(); |
| 19 | + // CountDownLatch countDownLatch = new CountDownLatch(1); |
| 20 | + // ExecutorService executorService = Executors.newCachedThreadPool(); |
| 21 | + |
| 22 | + // Future<Integer> future = executorService.submit(() -> sum()); |
| 23 | + // executorService.execute( () -> { |
| 24 | + // int result = sum(); |
| 25 | + // System.out.println("异步计算结果为:"+result); |
| 26 | + // countDownLatch.countDown(); |
| 27 | + // }); |
| 28 | + // executorService.shutdown(); |
| 29 | + // countDownLatch.await(); |
| 30 | + int result = CompletableFuture.supplyAsync(()-> sum()).join(); |
| 31 | + |
34 | 32 | //int result = sum(); //这是得到的返回值 |
35 | 33 | //int result = future.get(); |
36 | 34 | // 确保 拿到result 并输出 |
37 | | - //System.out.println("异步计算结果为:"+result); |
38 | | - |
39 | | - System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms"); |
40 | | - |
| 35 | + System.out.println("异步计算结果为:"+result); |
| 36 | + |
| 37 | + System.out.println("使用时间:" + (System.currentTimeMillis() - start) + " ms"); |
| 38 | + |
41 | 39 | // 然后退出main线程 |
42 | 40 | } |
43 | | - |
| 41 | + |
44 | 42 | private static int sum() { |
45 | 43 | return fibo(36); |
46 | 44 | } |
47 | | - |
| 45 | + |
48 | 46 | private static int fibo(int a) { |
49 | | - if ( a < 2) |
| 47 | + if (a < 2) |
50 | 48 | return 1; |
51 | | - return fibo(a-1) + fibo(a-2); |
| 49 | + return fibo(a - 1) + fibo(a - 2); |
52 | 50 | } |
53 | 51 | } |
0 commit comments