Question: :Java Programming Write a class Summer that computes the sum of numbers from 1 to n in parallel using multiple concurrent threads. The class interface

:Java Programming

Write a class Summer that computes the sum of numbers from 1 to n in parallel using multiple concurrent threads. The class interface has a public method:

/** *@param n the upper limit *@param k the number of threads *@return the sum 1 + 2 + ... + n computed with k threads */ int sum(int n, int k);

The sum 1+2+...+n is broken down in k intervals: [0, n/k], [n/k+1, 2*n/k], [2*n/k+1, 3*n/k],...,[(k-1)*n/k, n]. A "worker" thread with index j (from 0 to k-1) computes the partial sum of the interval [j*n/k, (j+1)*n/k].

After all worker threads finish summing their interval, the main thread adds all partial sums and returns the total sum.

Make sure it works. Test against the formula sum=n*(n+1)/2.

Use either ReentrantLock with Condition or use the Java object lock with wait/notify and "synchronized" methods/blocks (preferred solution).

Points will be deducted if race conditions are possible.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!