Requirements: It is necessary to execute multiple tasks asynchronously and obtain the results of each task. Determine whether to continue the following operations based on the task results
public static void main ( String [ ] args) {
List < CompletableFuture > objects = Collections . synchronizedList ( new ArrayList < > ( ) ) ;
ExecutorService es = Executors . newFixedThreadPool ( 3 ) ;
objects. add ( CompletableFuture . supplyAsync ( ( ) -> {
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
return "任务1" ;
} , es)
. handle ( ( result, e) -> {
System . out. println ( "结果和异常信息" + result+ "-error:" + e) ;
return result;
} ) ) ;
objects. add ( CompletableFuture . supplyAsync ( ( ) -> {
return "任务2" ;
} ) ) ;
CompletableFuture < Void > voidCompletableFuture = CompletableFuture . allOf ( objects. toArray ( new CompletableFuture [ objects. size ( ) ] ) ) ;
List < Object > collect = objects. stream ( ) . map ( CompletableFuture :: join ) . collect ( Collectors . toList ( ) ) ;
System . out. println ( "全部执行结果:" + collect) ;
System . out. println ( "是否全部完成:" + voidCompletableFuture. isDone ( ) ) ;
es. shutdown ( ) ;
}
Method 2 uses Future, example: Execute sequentially, wait until the result of the specified task is obtained before continuing to execute
ExecutorService executorService = Executors . newFixedThreadPool ( 3 ) ;
Future < String > submit = executorService. submit ( new Callable < String > ( ) {
@Override
public String call ( ) throws Exception {
Thread . sleep ( 3000 ) ;
return "我是任务1结果" ;
}
} ) ;
Future < String > submit2 = executorService. submit ( new Callable < String > ( ) {
@Override
public String call ( ) throws Exception {
Thread . sleep ( 2500 ) ;
return "我是任务2结果" ;
}
} ) ;
String s = submit. get ( ) ;
String s2 = submit2. get ( ) ;
System . out. println ( "任务1:" + s) ;
System . out. println ( "任务2:" + s2) ;
System . out. println ( "执行完成" ) ;
Implementation using CountDownLatch: An example of a race
CountDownLatch countDownLatch = new CountDownLatch ( 5 ) ;
ThreadPoolExecutor tp = new ThreadPoolExecutor ( 5 , 5 , 10 , TimeUnit . SECONDS , new LinkedBlockingDeque < > ( ) ) ;
tp. allowCoreThreadTimeOut ( true ) ;
for ( int i = 0 ; i < 5 ; i++ ) {
int finalI = i + 1 ;
Runnable runnable = new Runnable ( ) {
@Override
public void run ( ) {
Long ll = ( long ) ( Math . random ( ) * 1000 ) ;
try {
Thread . sleep ( ll) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} finally {
countDownLatch. countDown ( ) ;
System . out. println ( finalI + "号选手,完成了比赛!:" + ll + "秒:" + Thread . currentThread ( ) . getName ( ) ) ;
}
}
} ;
tp. submit ( runnable) ;
}
System . out. println ( "等待5个运动员都跑完....." ) ;
countDownLatch. await ( ) ;
tp. shutdown ( ) ;
System . out. println ( tp. isShutdown ( ) ) ;
System . out. println ( tp. isTerminated ( ) ) ;
System . out. println ( "所有人都跑完了,比赛结束。" ) ;