Usage scenarios: If you need to get the results of a thread, or do other things after the threads are finished, you can use callable and futrue
1. Define a thread pool to submit a single callable task to the thread pools
Executorservice threadpools=Executors.newsinglethreadexecutor (); Future<String> Future=threadpools.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {thread.sleep (2000);//simulated task processing 2S return"Hello"; } }); System.out.println ("Wait for the result ....." "); Try{System.out.println ("Get Results:" +future.get ());//2S After the task is completed get results}Catch(Exception e) {e.printstacktrace (); }
2.CompletionService is used to submit a set of callable tasks and get the results of each task
Executorservice Threadpools2=executors.newfixedthreadpool (10); Completionservice<Integer> completetionservice=NewExecutorcompletionservice<integer>(THREADPOOLS2); //Submit 10 Quests for(inti=1;i<=10;i++){ Final intseq=i; Completetionservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000)); returnseq; } }); } for(inti=1;i<=10;i++) { future<Integer>futures; Try{futures=Completetionservice.take (); System.out.println ("Get the task Result:" +futures.get ());//Get the results after the task is completed and which task is completed first}Catch(Exception e) {e.printstacktrace (); } }
Multithreading article seven: Get the results of a single service in a thread pool through callable and future