11package java0 .conc0303 ;
22
3- import java .util .concurrent .CountDownLatch ;
4- import java .util .concurrent .ExecutorService ;
5- import java .util .concurrent .Executors ;
6-
73/**
84 * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
95 * 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
@@ -18,17 +14,23 @@ public static void main(String[] args) throws Exception {
1814 long start =System .currentTimeMillis ();
1915 // 在这里创建一个线程或线程池,
2016 // 异步执行 下面方法
21- CountDownLatch countDownLatch = new CountDownLatch (1 );
22- ExecutorService executorService = Executors .newCachedThreadPool ();
17+ // CountDownLatch countDownLatch = new CountDownLatch(1);
18+ // ExecutorService executorService = Executors.newCachedThreadPool();
2319
2420 // Future<Integer> future = executorService.submit(() -> sum());
25- executorService .execute ( () -> {
26- int result = 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 ();
2730 System .out .println ("异步计算结果为:" +result );
28- countDownLatch .countDown ();
2931 });
30- executorService . shutdown ();
31- countDownLatch . await ();
32+ t1 . start ();
33+ t1 . join ();
3234 //int result = sum(); //这是得到的返回值
3335 //int result = future.get();
3436 // 确保 拿到result 并输出
0 commit comments