ImportJava. Util. concurrent. Callable;
ImportJava. Util. concurrent.CompletionService;
ImportJava. Util. concurrent. ExecutionException;
ImportJava. Util. concurrent. ExecutorCompletionService;
ImportJava. Util. concurrent. ExecutorService;
ImportJava. Util. concurrent. Executors;
ImportJava. Util. concurrent. Future;
Public class TestCompletionService {
Public static void main (String [] args) throws InterruptedException,
ExecutionException {
ExecutorService exec = Executors. newFixedThreadPool (10 );
CompletionServiceServ = new ExecutorCompletionService (exec );
For (int index = 0; index <5; index ++ ){
Final int NO = index;
Callable downImg = new Callable (){
Public String call () throws Exception {
Thread. sleep (long) (Math. random () * 10000 ));
Return "Downloaded Image" + NO;
}
};
Serv. submit (downImg );
}
Thread. sleep (1000*2 );
System. out. println ("Show web content ");
For (int index = 0; index <5; index ++ ){
Future task = serv. take ();
String img = (String) task. get ();
System. out. println (img );
}
System. out. println ("End ");
// Close the thread pool
Exec. shutdown ();
}
}
Consider the following scenarios: When browsing a webpage, the browser downloads the image files from the webpage using five threads. Due to the influence of image size, website access speed, and many other factors, the download time varies greatly. If the image is downloaded first, it is first displayed on the interface. Otherwise, the downloaded image is displayed later.
JavaConcurrent LibraryCompletionServiceYes
To meet the requirements of this scenario. This interface has two important methods: submit () and take (). Submit is used to submit a runnable or callable.
It is handed over to a thread pool for processing, while take is the Future object of the runnable or callable instance that has been executed. If it does not meet the requirements, it will wait.CompletionServiceThere is also a corresponding method poll, which is similar to take, but does not wait. If the requirements are not met, the null object is returned.