Callable and future in the Java thread pool

Source: Internet
Author: User

ImportJava.util.Random;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.CompletionService;ImportJava.util.concurrent.ExecutorCompletionService;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Callable Future completionservice Test * * The future results type and results of callable return * * Callable required Executorservice submit using Submit method * * Completionservice is used to submit a set of callable, where the Take method returns the completed callable task * *@authorDuwenlei **/ Public classCallablefuturetest {Private Static voidTestcallable ()throwsException {executorservice service=Executors.newsinglethreadexecutor (); Future<String> future = Service.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {thread.sleep (5000);//stop 5 Seconds to return                return"Hello";        }        }); System.out.println ("Wait for results"); System.out.println ("Get results:" +future.get ()); //System.out.println ("Get Results:" +future.get (1, timeunit.seconds));Service.shutdown (); }        Private Static voidTestcompletionservice ()throwsexception{Executorservice Executor= Executors.newfixedthreadpool (3); Completionservice<Integer> Service =Newexecutorcompletionservice<integer> (executor);//need a thread pool         for(inti = 1; I <= 10; i++) {            Final intSeq =i; Service.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000));//rest time, not sure.                    returnseq;        }            }); }         for(inti = 1; I <= 10; i++) {System.out.println (Service.take (). get ());    } executor.shutdown (); }         Public Static voidMain (string[] args) {Try{testcallable (); } Catch(Exception e) {e.printstacktrace (); }        Try{testcompletionservice (); } Catch(Exception e) {e.printstacktrace (); }    }}

Callable and future in the Java thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.