Completionservice is an abstract Java generic interface that is implemented by a Executorcompletionservice generic class that separates production tasks from the results of production tasks. The producer submits the task through submit, and the consumer production structure gets the results of the task back by take, and then does the other processing. Completionservice is commonly used in places where asynchronous operations are required, such as network requests, file IO, and other time-consuming operations. Executorcompletionservice maintains a future blockingqueue that submits a task. Executorcompletionservice combines executor (thread pool) and blockingqueue (blocking queues), using callable as the basic unit of the task, The whole process is that producers constantly put the callable task into the blocking right, executor as consumers constantly pull out the task to execute, and return the results; Here's a case to illustrate their use:
public class Mycompletionservice {
public static void Main (string[] args) throws Interruptedexception,
executionexception {
Executorservice exec = Executors.newfixedthreadpool (5);
completionservice<myobject> serv = new Executorcompletionservice<myobject> (
EXEC);
for (int index = 0; index < 5; index++) {
Final int id = index;
/** Task Execution Unit, task execution returns a struct, **/
callable<myobject> downimg = new Callable<myobject> () {
Public MyObject Call () throws Exception {
Simulate Execution Timeout task
Thread.Sleep (1000);
return new MyObject (ID, "Niuniu" + ID);
}
};
Serv.submit (DOWNIMG);
}
/** obtains a completed future from the Executorcompletionservice queue and obtains the structure from future **/
for (int index = 0; index < 5; index++) {
If the queue has a result to return, it is taken out to process, if there is no wait
future<myobject> task = Serv.take ();
MyObject mmyobject = Task.get ();
System.out.println ("myobject=" + mmyobject.tostring ());
}
System.out.println ("End");
Close the thread pool
Exec.shutdown ();
}
}
Class MyObject {
private int id;
private String name;
public MyObject (int ID, String name) {
This.id = ID;
THIS.name = name;
}
@Override
Public String toString () {
Return "MyObject [id=" + ID + ", name=" + name + "]";
}
}