File tree Expand file tree Collapse file tree
03concurrency/0301/src/main/java/java0/conc0303 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package java0 .conc0303 ;
22
3+ import java .util .concurrent .CountDownLatch ;
34import java .util .concurrent .ExecutorService ;
45import java .util .concurrent .Executors ;
5- import java .util .concurrent .Future ;
66
77/**
88 * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
@@ -18,14 +18,21 @@ public static void main(String[] args) throws Exception {
1818 long start =System .currentTimeMillis ();
1919 // 在这里创建一个线程或线程池,
2020 // 异步执行 下面方法
21+ CountDownLatch countDownLatch = new CountDownLatch (1 );
2122 ExecutorService executorService = Executors .newCachedThreadPool ();
22- Future <Integer > future = executorService .submit (() -> sum ());
23- executorService .shutdown ();
2423
24+ // Future<Integer> future = executorService.submit(() -> sum());
25+ executorService .execute ( () -> {
26+ int result = sum ();
27+ System .out .println ("异步计算结果为:" +result );
28+ countDownLatch .countDown ();
29+ });
30+ executorService .shutdown ();
31+ countDownLatch .await ();
2532 //int result = sum(); //这是得到的返回值
26- int result = future .get ();
33+ // int result = future.get();
2734 // 确保 拿到result 并输出
28- System .out .println ("异步计算结果为:" +result );
35+ // System.out.println("异步计算结果为:"+result);
2936
3037 System .out .println ("使用时间:" + (System .currentTimeMillis ()-start ) + " ms" );
3138
You can’t perform that action at this time.
0 commit comments