|
1 | 1 | package java0.conc0303; |
2 | 2 |
|
| 3 | +import java.util.concurrent.atomic.AtomicReference; |
| 4 | + |
3 | 5 | import java.util.concurrent.CountDownLatch; |
4 | 6 |
|
| 7 | + |
5 | 8 | /** |
6 | 9 | * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池, |
7 | 10 | * 异步运行一个方法,拿到这个方法的返回值后,退出主线程? |
8 | 11 | * 写出你的方法,越多越好,提交到github。 |
9 | | - * |
| 12 | + * <p> |
10 | 13 | * 一个简单的代码参考: |
11 | 14 | */ |
12 | 15 | 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(); |
17 | 20 | // 在这里创建一个线程或线程池, |
18 | 21 | // 异步执行 下面方法 |
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 | + |
22 | 41 | // 确保 拿到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 | + |
27 | 49 | // 然后退出main线程 |
28 | 50 | } |
29 | | - |
| 51 | + |
30 | 52 | private static int sum() { |
31 | 53 | return fibo(36); |
32 | 54 | } |
33 | | - |
| 55 | + |
34 | 56 | private static int fibo(int a) { |
35 | | - if ( a < 2) |
| 57 | + if (a < 2) |
36 | 58 | return 1; |
37 | | - return fibo(a-1) + fibo(a-2); |
| 59 | + return fibo(a - 1) + fibo(a - 2); |
38 | 60 | } |
39 | 61 | } |
0 commit comments