Java concurrency and multithreading 2:3 ways to implement the sum of arrays

Source: Internet
Author: User

This article shows an example of a summation of 3 arrays.


Example 1: Single thread
Example 2: Multithreading, synchronous summation (blocking if no calculation is complete)
Example 3: Multithreading, asynchronous summation (first summing up completed calculations)


Example 1-code
Package Cn.fansunion.executorservice;public class Basiccaculator {public static long sum (int[] numbers) {    Long sum = 0 ;    for (int i=0;i<numbers.length;i++) {    sum + = Numbers[i];    }    return sum;}}




Example 2-code
Executoreservice provides the submit () method, passing a callable, or runnable, back to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete.
Package Cn.fansunion.executorservice;import Java.util.arraylist;import Java.util.list;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.Future; Import java.util.concurrent.futuretask;//The sum of the concurrent computed arrays, "Synchronize" sum public class Concurrentcalculator {private Executorservice exec;//this place, is purely "wishful thinking", "parallel execution" is not controlled by us, depending on the operating system of "attitude" private int cpucorenumber;private list<future<long>> tasks = new Arraylist<future<long>> (); class Sumcalculator implements callable<long> {private int[] numbers;private int start;private int end;public sumcalculator (final int[] numbers, int start, int end) {this.numbers = Nu Mbers;this.start = Start;this.end = end;} Public Long Call () throws Exception {Long sum = 0l;for (int i = start; i < end; i++) {sum + = numbers[i];} return sum;}} Public Concurrentcalculator () {cpucorenumber = Runtime.getruntime (). AvailableprocessoRS (); exec = Executors.newfixedthreadpool (cpucorenumber);} Public Long sum (final int[] numbers) {//Split task based on number of CPU cores, create futuretask and commit to executorfor (int i = 0; i < Cpucorenumber; i++) {int increment = Numbers.length/cpucorenumber + 1;int start = increment * I;int end = increment * i + increment;if (end > numbers.length) end = Numbers.length; Sumcalculator Subcalc = new Sumcalculator (numbers, start, end); futuretask<long> task = new futuretask<long> (SUBCALC); Tasks.add (Task); if (!exec.isshutdown ()) { Exec.submit (Task);}} return GetResult ();} /** * Iterates over each task, obtains parts and, adds returns */public long GetResult () {Long result = 0l;for (future<long> task:tasks) {try {//If the calculation is not completed Block Long subsum = Task.get (); result + = Subsum;} catch (Interruptedexception e) {e.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ()}} return result;} public void Close () {Exec.shutdown ();}}






Example 3-code
In the first example, the GetResult () method iterates over the Futuretask array, and the current thread blocks if the task is not completed.
If we want to add the results to result after any word task is completed, instead of waiting for each task to complete, you can make completionservice.
The task performed by the producer submit (). The consumer take () completed tasks and processes their results in the order in which they were completed. That is, the take method that calls Completionservice returns the result of putting the task back in the completed order.
Completionservice internally maintains a blocking queue blockingqueue, and if no task is completed, the Take () method is blocked.
To modify just the example 2, use Completionservice:
Package Cn.fansunion.executorservice;import Java.util.concurrent.callable;import Java.util.concurrent.completionservice;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorcompletionservice;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;//concurrency computes the sum of the array, "Async" sums public class Concurrentcalculatorasync {private Executorservice Exec;private completionservice<long> completionservice;//This place, is purely "wishful thinking", "parallel execution" is not controlled by us, depending on the operating system of "attitude" private int Cpucorenumber;class Sumcalculator implements callable<long> {private int[] numbers;private int start;private int End;public sumcalculator (final int[] numbers, int start, int end) {this.numbers = Numbers;this.start = Start;this.end = END;} Public Long Call () throws Exception {Long sum = 0l;for (int i = start; i < end; i++) {sum + = numbers[i];} return sum;}} Public Concurrentcalculatorasync () {cpucorenumber = Runtime.getruntime (). Availableprocessors (); exec = Executors.newfixedthreadpool (CpucoRenumber); completionservice = new executorcompletionservice<long> (exec);} Public Long sum (final int[] numbers) {//Split task based on number of CPU cores, create futuretask and commit to executorfor (int i = 0; i < Cpucorenumber; i++) {int increment = Numbers.length/cpucorenumber + 1;int start = increment * I;int end = increment * i + increment;if (end > numbers.length) {end = Numbers.length;} Sumcalculator Subcalc = new Sumcalculator (numbers, start, end); if (!exec.isshutdown ()) {Completionservice.submit ( SUBCALC);}} return GetResult ();}  /** * Iterates over each task, obtains parts and, adds returns */public long GetResult () {Long result = 0l;for (int i = 0; i < Cpucorenumber; i++) {try {long Subsum = Completionservice.take (). get (); result + = Subsum; System.out.println ("subsum=" +subsum+ ", result=" +result);} catch (Interruptedexception e) {e.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ()}} return result;} public void Close () {Exec.shutdown ();}}




Run code
Package Cn.fansunion.executorservice;import java.math.bigdecimal;//Array summation 3 Demopublic class Arraysumdemo {public static void Main (string[] args) {int n = 200000000;int[] numbers = new int[n];for (int i=1;i<=n;i++) {numbers[i-1]=i;} Basic (numbers); Long time = System.currenttimemillis (); Concurrentcaculatorasync (numbers); Long endtime= System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Multi-core parallel computation, asynchronous addition:" +time (Time,endtime)); Long time2 = System.currenttimemillis (); concurrentcaculator (numbers); long Endtime2=system.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Multi-core parallel computing, simultaneous addition:" +time (Time2,endtime2));} private static void Basic (int[] numbers) {Long time1 = System.currenttimemillis (); long sum=basiccaculator.sum (numbers); Long endTime1 = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Single Thread:" +time (time1,endtime1)); System.out.println ("Sum:" +sum);} private static double time (long time, long EndTime) {long costtime = Endtime-time; BigDecimal bd = new BigDecimal (costtime);//originally thinking, to convert milliseconds into seconds, and finally found that the calculation is too fast BigDecimal unit = new BigdecimaL (1L); BigDecimal s= bd.divide (unit,3); return S.doublevalue ();} Parallel computation, "synchronous" summation private static void Concurrentcaculator (int[] numbers) {Concurrentcalculator calc = new Concurrentcalculator (); Long sum = calc.sum (numbers); SYSTEM.OUT.PRINTLN (sum); Calc.close ();} Parallel computation, "async" summation private static void Concurrentcaculatorasync (int[] numbers) {Concurrentcalculatorasync calc = new Concurrentcalculatorasync (); Long sum = calc.sum (numbers); System.out.println ("Sum:" +sum); Calc.close ();}}




Console Output
Single Thread: 93.0
sum:20000000100000000
subsum=3750000175000002,result=3750000175000002
subsum=1250000075000001,result=5000000250000003
subsum=6250000275000003,result=11250000525000006
subsum=8749999574999994,result=20000000100000000
sum:20000000100000000
Multi-core parallel computing, asynchronous addition: 786.0
20000000100000000
Multi-core parallel computing, simultaneous addition: 650.0


Personal views: 3 code time for reference only, did not exclude interference factors.
In general, single-threaded execution is faster, because the "array sum" itself does not require additional resources and is not blocked.
Instead, multiple threads increase the time overhead of "thread scheduling".


You can also see that the CPU calculation is very fast. The "200000000" 200 million integers add up to a time of less than 0.1 seconds.


episode
When I first looked at the code, I misunderstood it. Think "the number of CPU cores split task", this time "multithreading" is "parallel".
In fact, not necessarily, except to look at the CPU's nuclear number, but also to see the operating system allocation.
Split tasks based on number of CPU cores, create futuretask and submit to Executor
for (int i = 0; i < Cpucorenumber; i++) {


}
At first, I was thinking of "single thread", "multi-core parallel + multi-threaded concurrency", "single core + multi-threaded concurrency", and several cases to achieve "array summation".
In the end, I felt like I was thinking more. "Parallel" should not be controlled by oneself, can only control is "single thread" or "multithreading".

"Java Concurrency Programming-executor framework" in this article, "Example: parallel computation of arrays and." ”This has misled me, and there is no guarantee of "parallel computing".
Friendship Hint: the article on the network, only for the reference study, needs own judgment.

On java-multicore-parallel-multi-threading, I initially thought that "multithreading can be executed in parallel, but not under our own control, depending on the operating system."




some views of netizens


View 1:
Can a Java thread run on more than one CPU core?

I have always thought that the answer to this question is yes, that is to say it can run on multicore.
But one day I saw such a theory, I immediately destroyed the three views.


The JVM is in the operating system as a process, and all Java threads are running from this JVM process.
So Java threads can only run on one core at a time.


That's a big blow to me, I can't accept it. So I began to prove the multiple. Online Search with friends to discuss,
Finally confirms that Java threads can run on multicore, why?
The following sentence will awaken the dream person:
The modern OS takes the thread as the smallest dispatch unit and the process as the smallest unit of resource allocation. The process is inactive in Windows,
Just as a container for threads.


That is, all threads in Java are indeed in the JVM process, but the CPU is scheduling the threads in the process.


View 2:
Can multithreading in Java be executed in parallel on a multi-CPU machine? Note that I'm not talking about concurrent execution OH.
We write a multithreaded program in Java, we start a JVM process, so these threads are in this JVM process, I do not know at the same time, can have multiple CPUs running the same process, in parallel to execute the different threads in the same process? I've been wondering.

Your idea is right, the CPU is to cater to the multi-threaded operating system to improve the system's computational efficiency. But the task of assigning tasks to individual cores is not Java and the JVM but the operating system.
That is, multiple threads that you execute may be assigned to run in the same CPU core. It is also possible to run on a different CPU. If you can control the allocation of the CPU, it should also be the operating system API to achieve.


I created a thread in Java, when both the main thread and the child thread are running, which means that the dual-core CPU might run the two threads in parallel at the same point in time.
I turned a lot of Java on the multi-threaded chapters, does not seem to say that multi-core CPU running Java Multi-threading, seems to have been a single core for the explanation, so I always think it may be concurrent rather than parallel?

No, you have to separate your software thread from the CPU processing thread of your computer. Simply put, you can't control the CPU's allocation of tasks.

More code Examples
Http://git.oschina.net/fansunion/Concurrent (in gradual update)


Resources:
Java Concurrency Programming-executor framework
http://www.iteye.com/topic/366591


Can a Java thread run on more than one CPU core?
http://blog.csdn.net/maosijunzi/article/details/42527553


Can multithreading in Java execute in parallel on multiple CPUs? Note that I'm not talking about concurrent execution OH
Http://zhidao.baidu.com/link?url=e11sEOSNFoLTfVyP-5FfpktIXEgbMQkbLAzvgh8mn4V16n_qQas89voj5gVhOEkho0jRA7fp_ Vbnelxkgeqcdroxgkcu6xawauniqpcwg33

Java concurrency and multithreading 2:3 ways to implement the sum of arrays

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.