Java uses callable and future to compute sums in parallel

Source: Internet
Author: User

Content: In Java, using callable to perform thread calculations with return results, using the future to represent the results of asynchronous computations, calculate the sum of long sums in different ranges separately, and similar ideas can be used for reference to places that require a lot of computation.

public class Sums {public    static class Sum implements Callable<long> {private final Long from;private final Lon G To;public Sum (long from, long to) {This.from = From;this.to = to;} @Overridepublic long Call () throws Exception {long ans = 0;for (long i = from; I <= to; i++) ans + = I;return ans;}} public static void Main (string[] args) throws Interruptedexception, executionexception {executorservice executor = Execut Ors.newfixedthreadpool (2); list<future<long>> ans = executor.invokeall (arrays.aslist (new sum (0, $), new sum (10000, 100000), New sum ( 1000000, 1000000)); Executor.shutdown (); Long sum = 0;for (future<long> i:ans) {Long tmp = I.get (); SYSTEM.OUT.PRINTLN (TMP); sum + = tmp;} System.out.println ("sum:" + sum);}}


Java uses callable and future to compute sums in parallel

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.