File tree Expand file tree Collapse file tree 1 file changed +28
-5
lines changed
03concurrency/0301/src/main/java/java0/conc0303 Expand file tree Collapse file tree 1 file changed +28
-5
lines changed Original file line number Diff line number Diff line change 11package java0 .conc0303 ;
22
3+ import java .util .Random ;
4+ import java .util .concurrent .*;
5+
36/**
47 * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
58 * 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
912 */
1013public class Homework03 {
1114
12- public static void main (String [] args ) {
15+ public static void main (String [] args ) throws ExecutionException , InterruptedException {
1316
1417 long start =System .currentTimeMillis ();
1518 // 在这里创建一个线程或线程池,
1619 // 异步执行 下面方法
17-
18- int result = sum (); //这是得到的返回值
19-
20+ int result = CompletableFuture .supplyAsync (()-> {
21+ System .out .println ("1.CompletableFuture" );
22+ return sum ();
23+ }).join ();;
2024 // 确保 拿到result 并输出
2125 System .out .println ("异步计算结果为:" +result );
22-
26+ FutureTask <Integer > task = new FutureTask <Integer >(new Callable <Integer >() {
27+ @ Override
28+ public Integer call () throws Exception {
29+ System .out .println ("2.FutureTask" );
30+ return sum ();
31+ }
32+ });
33+ new Thread (task ).start ();
34+ System .out .println ("异步计算结果为:" +task .get ());
35+ ExecutorService executor = Executors .newSingleThreadExecutor ();
36+ Future <Integer > fresult = executor .submit (new Callable <Integer >() {
37+ public Integer call () throws Exception {
38+ System .out .println ("3.Future" );
39+ return sum ();
40+ }
41+ });
42+ executor .shutdown ();
43+ System .out .println ("异步计算结果为:" +fresult .get ());
44+
45+
2346 System .out .println ("使用时间:" + (System .currentTimeMillis ()-start ) + " ms" );
2447
2548 // 然后退出main线程
You can’t perform that action at this time.
0 commit comments