Using concurrent programming, the computation of large amounts of data and
Implementation code:
PackageTj.pojo.generate.main;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.FutureTask; Public classConcurrentcalculator {PrivateExecutorservice exec; Private intCpucorenumber; Privatelist<future<long>> tasks =NewArraylist<future<long>>(); //Inner class classSumcalculatorImplementsCallable<long> { Private int[] numbers; Private intstart; Private intend; PublicSumcalculator (Final int[] numbers,intStartintend) { This. Numbers =numbers; This. Start =start; This. end =end; } @Override PublicLong Call ()throwsException {Long sum= 0L; for(inti = start; I < end; i++) {sum+=Numbers[i]; } System.out.println (String.Format ("%s~%s and for%s", start, end, sum)); returnsum; } } PublicConcurrentcalculator () {Cpucorenumber=runtime.getruntime (). Availableprocessors (); System.out.println ("Number of CPU cores:" +cpucorenumber); EXEC=Executors.newfixedthreadpool (Cpucorenumber); } PublicLong sum (Final int[] numbers) { for(inti = 0; i < Cpucorenumber; i++) { intincrement = Numbers.length/cpucorenumber + 1; intstart = increment *i; intEnd = Start +increment; if(End >numbers.length) {End=numbers.length; } sumcalculator Task=Newsumcalculator (numbers, start, end); Futuretask<Long> future =NewFuturetask<long>(Task); Tasks.add (future); System.out.println ("Add a task with the number of total task:" +tasks.size ()); if(!Exec.isshutdown ()) {Exec.submit (future); //Executoreservice provides the Submit () method, passing a callable, or runnable, back to the future. //Exec.submit (Task);}} System.out.println ("Task assignment complete, number of total task:" +tasks.size ()); returnGetResult (); } Publiclong GetResult () {Long sums= 0L; for(future<long>task:tasks) { Try{Long sum=Task.get (); Sums+=sum; System.out.println ("Total Current:" +sums); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } } returnsums; } Public voidClose () {Exec.shutdown (); }}
Where, in line 62nd ~ 64th of the Code, the functionality of the Executoreservice.submit (Runnable Task) method is not known.
Both the futuretask<long> future and the Sumcalculator task implement the Runnable interface, resulting in the process not ending when the code is called.
Passed the futuretask<long> future before it was executed correctly.
Exec.submit (future); // Executoreservice provides the Submit () method, passing a callable, or runnable, back to the future. // Exec.submit (Task);
Test method:
Public Static void Test () { intnewint[+]; for (int i = 0; i <; i++) { = i + 1; } New tj.pojo.generate.main.ConcurrentCalculator (); = cc.sum (numbers); System.out.println ("1~100" + sum); Cc.close (); }
Implementation code for the Futuretask:
public class Futuretask<v> implements Runnablefuture<v>
The Futuretask class implements the Runnablefuture interface, the implementation code of the Runnablefuture interface:
Public interface runnablefuture<v> extends Runnable, future<v> {
void run ();
}
It can be seen that runnablefuture inherits the Runnable interface and the future interface, and Futuretask implements the Runnablefuture interface.
So it can be executed as runnable by thread, and can get callable return value as future.
In fact, Futuretask is a unique implementation class for the future interface.
Two implementation forms of concurrent programming:
1): Use Callable+future to get execution results
Public classTest { Public Static voidMain (string[] args) {Executorservice executor=Executors.newcachedthreadpool (); Task Task=NewTask (); Future<Integer> result =Executor.submit (Task); Executor.shutdown (); Try{Thread.Sleep (1000); } Catch(interruptedexception E1) {e1.printstacktrace (); } System.out.println ("Main thread is performing tasks"); Try{System.out.println ("Task Run Result" +result.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } System.out.println ("All Tasks Completed"); }}classTaskImplementsCallable<integer>{@Override PublicInteger Call ()throwsException {System.out.println ("Child threads are being evaluated"); Thread.Sleep (3000); intsum = 0; for(inti=0;i<100;i++) Sum+=i; returnsum; }}
2): Use Callable+futuretask to get execution results
Public classTest { Public Static voidMain (string[] args) {//The first wayExecutorservice executor =Executors.newcachedthreadpool (); Task Task=NewTask (); Futuretask<Integer> Futuretask =NewFuturetask<integer>(Task); Executor.submit (Futuretask); Executor.shutdown (); //The second way, note that this approach is similar to the first, except that one is using Executorservice, one using thread /*Task task = new Task (); futuretask<integer> futuretask = new futuretask<integer> (Task); Thread thread = new Thread (futuretask); Thread.Start ();*/ Try{Thread.Sleep (1000); } Catch(interruptedexception E1) {e1.printstacktrace (); } System.out.println ("Main thread is performing tasks"); Try{System.out.println ("Task Run Result" +futuretask.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); } System.out.println ("All Tasks Completed"); }}classTaskImplementsCallable<integer>{@Override PublicInteger Call ()throwsException {System.out.println ("Child threads are being evaluated"); Thread.Sleep (3000); intsum = 0; for(inti=0;i<100;i++) Sum+=i; returnsum; }}
[Concurrent programming] concurrent programming the second chapter: the use of concurrent programming, to achieve the computation of large amounts of data and