Java Multi-Threading and Concurrency Library Advanced application-callable and future application

Source: Internet
Author: User

Callable such a task can return results, and the returned results can be taken from the future.

The result type obtained by >future and the result type returned by callable must be the same, which is achieved by generics.

>completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task.

  Like I planted a few pieces of wheat at the same time, and then waited for the harvest. When the harvest is ripe, it is the first to reap the wheat.

  future<string> future = Threadpool.submit (new  callable< String> () {@Override  public String Call () throws   Exception {Threa                D.sleep ( 2000 return  "Hello" ;        }        });        SYSTEM.OUT.PRINTLN ( wait result  try   {System.out.println ( "Get results:        "+future.get ());  catch   (Exception e) {E.printstacktra        CE (); }

This type of hair is the future to actively ask callable whether it produces results

>completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task.

Executorservice executor = Executors.newfixedthreadpool (10); Completionservice<Integer> Completionservice =NewExecutorcompletionservice<>(executor);  for(inti = 0;i<10;i++){            Final intSeq =i; Completionservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000)); returnseq;        }            }); }         for(inti = 0;i<10;i++) {//waiting to get results            Try{System.out.println (Completionservice.take (). get ()); } Catch(Exception e) {e.printstacktrace ();        }; }

Java Multi-Threading and Concurrency Library Advanced application-callable and future application

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.