Use of Completionservice
When we use Executorservice to create a thread pool, if we perform multiple callable tasks, each callable task will produce a future, if we need to deal with the results of these tasks, Then you need to put these future into a linear table for subsequent data processing.
With Completionservice, we don't have to artificially create linear tables to save these future, Compleservice is a more advanced eexcutorservice, which itself comes with a thread-safe linear table, without the need for additional user creation. It provides two methods for extracting results from a linear table: poll () is non-blocking, returns NULL if no results are present, and the current thread continues to run without blocking; Take () is blocked, and if no result is currently present, the current thread is blocked until a result is fetched and returned, and the current thread continues to run.
The code is as follows:
Importjava.util.concurrent.*; Public classCompletionservicetest { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {executorservice executorservice=Executors.newcachedthreadpool (); Completionservice<Integer> Completionservice =NewExecutorcompletionservice<integer>(Executorservice); for(inti=0; i<5; i++) {Completionservice.submit (NewTask ()); } executorservice.shutdown (); intCount=0, Index=1; while(Count < 5) { future<Integer> result =Completionservice.poll (); if(Result = =NULL) {System.out.println (index+ "No tasks found to be completed"); }Else{System.out.println (index+ "generated a random number" +result.get ()); Count++; } Index++; TimeUnit.SECONDS.sleep (2); } }}
import Java.util.Random; import java.util.concurrent.Callable; import Java.util.concurrent.TimeUnit; public class Task implements callable<integer> {@ Override public Integer call () throws Exception {random random = new Random (); TimeUnit.SECONDS.sleep ( 1); return Random.nextint (); }}
The results of the operation are as follows:
1 did not find a completed task 2 produced a random number 10687299463 produced a random number-7540724284 produced a random number-7111208095 produced a random number 16965230686 produced a random number 1409 817456
Java Thread Completionservice