Java Threading callable_future_executors thread pool usage

Source: Internet
Author: User

1. Create a task first

 PackageCom.currentPro.task;Importjava.util.concurrent.Callable; Public classMuniustaskImplementsCallable<integer>{    PrivateInteger number;  PublicMuniustask (Integer number) { This. Number =Number ; } @Override PublicInteger Call ()throwsException {intresult; Result= Number-1; returnresult; }}

2. Create Taskexecutor

 Public class muniustaskexecutor {    protected  executorservice executors;    Initializes the thread pool     public   muniustaskexecutor (Integer threadnums) {        this. Executors = Executors.newfixedthreadpool (threadnums);    }}

3. Testing

 PackageCom.currentPro.task;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Random;Importjava.util.concurrent.ExecutionException;Importjava.util.concurrent.Future; Public classTasktest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {plustaskexecutor plustaskexecutor=NewPlustaskexecutor (10); List<Future<Integer>> resultlist =NewArraylist<future<integer>> (); Random Random=NewRandom ();  for(inti = 0; I < 4; i++) {Integer number= Random.nextint (10); System.out.println ("Random Value:" +Number ); Muniustask M1=Newmuniustask (number); Future<Integer> result =PlusTaskExecutor.executors.submit (M1);        Resultlist.add (result); }         for(future<integer>future:resultlist) {System.out.println ("Future result is-" + "-" + future.get () + "; and Task done is "+Future.isdone ()); }            }}

4. Results

Random value: 2random value:0Random value:2Random value:8-  true-   True-  true-  true

Java Threading callable_future_executors thread pool usage

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.