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