Open zhamri opened 4 years ago
import java.util.Random;
public class ParallelSum extends Thread
{
private int[] arr;
private int low, high, partial;
public ParallelSum(int[] arr, int low, int high)
{
this.arr = arr;
this.low = low;
this.high = Math.min(high, arr.length);
}
public static int parallelSum(int[] arr)
{
return parallelSum(arr, Runtime.getRuntime().availableProcessors());
}
public static int parallelSum(int[] arr, int threads)
{
int size = (int) Math.ceil(arr.length * 1.0 / threads);
ParallelSum[] sums = new ParallelSum[threads];
for (int i = 0; i < threads; i++) {
sums[i] = new ParallelSum(arr, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (ParallelSum sum : sums) {
sum.join();
}
} catch (InterruptedException e) { }
int total = 0;
return total;
}
public static void main(String[] args)
{
Random r = new Random();
int[] arr = new int[10];
int sum =0;
for (int i = 0; i < arr.length; i++) {
int a = r.nextInt(10);
System.out.println("+"+a);
sum = sum + a ;
}
long start = System.currentTimeMillis();
ParallelSum.parallelSum(arr);
System.out.println("Total: "+sum);
System.out.println("Total Execution Time For Parallel Sum: " + (System.currentTimeMillis() - start) + "ms");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Issue;
import java.util.Random;
/**
*
* @author MICKY
*/
class Summing implements Runnable {
int a;
public Summing(int a) {
this.a = a;
}
public void run() {
addRondom();
}
public void addRondom() {
Random rand = new Random();
int n = rand.nextInt(10) + 1;
System.out.print(n+",");
synchronized (this) {
a += n;
}
}
}
public class issue12{
public static void main(String[] args) throws InterruptedException {
System.out.println("The ten random values are: ");
int base = 0;
Summing sum2 = new Summing(base);
Thread t1 = new Thread(sum2);
Thread t2 = new Thread(sum2);
Thread t3 = new Thread(sum2);
Thread t4 = new Thread(sum2);
Thread t5 = new Thread(sum2);
Thread t6 = new Thread(sum2);
Thread t7 = new Thread(sum2);
Thread t8 = new Thread(sum2);
Thread t9 = new Thread(sum2);
Thread t10 = new Thread(sum2);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
t7.join();
t8.join();
t9.join();
t10.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("\nSum: " + sum2.a);
long start = System.currentTimeMillis();
Thread.sleep(2000);
long elapsedTimeMillis = System.currentTimeMillis() - start;
System.out.println("\nExecution time: "+elapsedTimeMillis);
}
}
Tan Cheng Yi 253814
import java.util.Random;
public class parallelSum {
public static void main(String[] args) {
Random rand = new Random();
int[] arr=new int[10];
for (int i = 0; i < arr.length; i++){
arr[i]=rand.nextInt();
}
long start = System.currentTimeMillis();
System.out.println("Total: "+pSum.parallelSum(arr));
long end=System.currentTimeMillis();
System.out.println("Execution Time in Milisecond: " + (end-start));
}
}
class pSum extends Thread{
private int[] arr;
private int low, high, partial;
public pSum(int[] arr, int low, int high)
{
this.arr = arr;
this.low = low;
this.high = Math.min(high, arr.length);
}
public int getPartialSum()
{
return partial;
}
public void run()
{
partial = sum(arr);
}
public static int sum(int[] arr)
{
int low=0;
int high=arr.length;
int total = 0;
for (int i = low; i < high; i++) {
total += arr[i];
}
return total;
}
public static int parallelSum(int[] arr)
{
return parallelSum(arr, Runtime.getRuntime().availableProcessors());
}
public static int parallelSum(int[] arr, int threads)
{
int size = (int) Math.ceil(arr.length * 1.0 / threads);
pSum[] sums = new pSum[threads];
for (int i = 0; i < threads; i++) {
sums[i] = new pSum(arr, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (pSum sum : sums) {
sum.join();
}
} catch (InterruptedException e) { }
int total = 0;
for (pSum sum : sums) {
total += sum.getPartialSum();
}
return total;
}
}
Ong Xun Sheng 253881
package com.xunsheng;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// write your code here
long start = System.currentTimeMillis();
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int numbers[] = new int[10];
Random random = new Random();
for(int i = 0; i < 10; i++){
int num = random.nextInt();
numbers[i] = num;
}
ParallelSum ps = new ParallelSum(numOfProcessors);
System.out.println("Total : " + ps.parallelSum(numbers));
long end = System.currentTimeMillis();
System.out.println("Time taken in milliseconds : " + (end-start));
}
}
class ParallelSum {
private ParallelWorker[] sums;
private int numOfThreads;
public ParallelSum(int numOfThreads) {
this.sums = new ParallelWorker[numOfThreads];
this.numOfThreads = numOfThreads;
}
public int parallelSum(int[] nums) {
int size = (int) Math.ceil(nums.length * 1.0 / numOfThreads);
for (int i = 0; i < numOfThreads; i++) {
sums[i] = new ParallelWorker(nums, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (ParallelWorker sum : sums) {
sum.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int total = 0;
for (ParallelWorker sum : sums) {
total += sum.getPartialSum();
}
return total;
}
}
class ParallelWorker extends Thread {
private int[] nums;
private int low;
private int high;
private int partialSum;
public ParallelWorker(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
public int getPartialSum() {
return partialSum;
}
@Override
public void run() {
partialSum = 0;
for (int i = low; i < high; i++) {
partialSum += nums[i];
}
}
}
import java.util.Random;
public class Summation extends Thread {
private int[] arr;
private int low, high, partial;
public Summation(int[] arr, int low, int high)
{
this.arr = arr;
this.low = low;
this.high = Math.min(high, arr.length);
}
public int getPartialSum()
{
return partial;
}
public void run()
{
partial = sum(arr, low, high);
}
public static int sum(int[] arr)
{
return sum(arr, 0, arr.length);
}
public static int sum(int[] arr, int low, int high)
{
int total = 0;
for (int i = low; i < high; i++) {
total += arr[i];
}
return total;
}
public static int parallelSum(int[] arr)
{
return parallelSum(arr, Runtime.getRuntime().availableProcessors());
}
public static int parallelSum(int[] arr, int threads)
{
int size = (int) Math.ceil(arr.length * 1.0 / threads);
Summation[] sums = new Summation[threads];
for (int i = 0; i < threads; i++) {
sums[i] = new Summation(arr, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (Summation sum : sums) {
sum.join();
}
} catch (InterruptedException e) { }
int total = 0;
for (Summation sum : sums) {
total += sum.getPartialSum();
}
return total;
}
public static void main(String[] args)
{
Random rand = new Random();
int[] arr = new int[100000000];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(101) + 1; // 1..100
}
long start = System.currentTimeMillis();
Summation.sum(arr);
System.out.println("Single: " + (System.currentTimeMillis() - start)); // Single: 44
start = System.currentTimeMillis();
Summation.parallelSum(arr);
System.out.println("Parallel: " + (System.currentTimeMillis() - start)); // Parallel: 25
}
}
TAN WEI DI 259296
import java.util.Random;
public class ParallelSum {
private static int done = 0;
private static int total = 0;
public static void main(String[] args){
long startTime = System.currentTimeMillis();
int[] arrNumber = new int[10];
for(int i=0; i <arrNumber.length;i++) {
Thread t_random = new Thread(()->{
int n_number = new Random().nextInt(100);
total += n_number;
System.out.println(Thread.currentThread().getName()+" Number : "+n_number);
done++;
});
t_random.start();
}
while (true) {
System.out.print("");
if(done==arrNumber.length){
System.out.print("Total Number : "+total);
break;
}
}
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println("\nExecution time in milliseconds: " + timeElapsed);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package parallelsum;
/**
*
* @author master lab
*/
import java.time.Clock;
/**
* This class allows us to compute the sum of an array using multiple threads.
*
* @author Sathish Gopalakrishnan
*
*/
public class ParallelSum extends Thread {
// we want to compute ans as sum[lo]+sum[lo+1]...+sum[hi-1]
private int lo;
private int hi;
private long ans = 0;
private int[] arr;
/**
*
* @param a
* array to sum
* @param lo
* is the index to start summing from
* @param hi
* is the index to stop computing the sum at (a[hi] is not part
* of the sum)
*/
ParallelSum(int[] a, int lo, int hi) {
this.arr = a;
this.lo = lo;
this.hi = hi;
this.ans = 0;
}
/**
* Actually compute the sum
*/
public void run() {
for (int idx = lo; idx < hi; idx++) {
ans += arr[idx];
}
// System.out.println(ans);
}
/**
* Compute the sum of an array
*
* @param arr
* array to sum
* @return the sum of the elements in arr
* @throws InterruptedException
*/
public static long sum(int[] arr) throws InterruptedException {
int len = arr.length;
long ans = 0;
int numThreads = 4;
ParallelSum[] ts = new ParallelSum[numThreads];
for (int i = 0; i < numThreads; i++) {// do parallel computations
ts[i] = new ParallelSum(arr, i * len / numThreads, (i + 1) * len / numThreads);
ts[i].start(); // start not run
}
for (int i = 0; i < numThreads; i++) { // combine results
ts[i].join(); // wait for helper to finish!
ans += ts[i].ans;
}
return ans;
}
public static void main(String[] args) {
Clock timingClock = Clock.systemUTC();
int len = 102045;
long ans = 0;
int[] arr = new int[len];
for (int i = 0; i < len; i++)
arr[i] = i + 1;
long start = timingClock.millis();
try {
ans = sum(arr);
} catch (InterruptedException e) {
System.out.println("Hello! We were interrupted.");
}
long end = timingClock.millis();
System.out.println(ans + " computed in " + (end - start) + "ms");
}
}
public class ParallelWorker extends Thread {
private int[] nums;
private int low;
private int high;
private int partialSum;
public ParallelWorker(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
public int getPartialSum() {
return partialSum;
}
@Override
public void run() {
partialSum = 0;
for (int i = low; i < high; i++) {
partialSum += nums[i];
}
}
}
public class ParallelSum {
private ParallelWorker[] sums;
private int numOfThreads;
public ParallelSum(int numOfThreads) {
this.sums = new ParallelWorker[numOfThreads];
this.numOfThreads = numOfThreads;
}
public int parallelSum(int[] nums) {
int size = (int) Math.ceil(nums.length * 1.0 / numOfThreads);
for (int i = 0; i < numOfThreads; i++) {
sums[i] = new ParallelWorker(nums, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (ParallelWorker sum : sums) {
sum.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int total = 0;
for (ParallelWorker sum : sums) {
total += sum.getPartialSum();
}
return total;
}
}
import java.util.Random;
public class TestParallel {
public static void main(String[] args) {
Random random = new Random();
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int[] nums = new int[11];
for (int i = 1; i < nums.length; i++) {
nums[i] = random.nextInt(101) + 1;
System.out.println("Random No " + i + ": " + nums[i]);
}
long start = System.currentTimeMillis();
ParallelSum parallelSum = new ParallelSum(numOfProcessors);
System.out.println("Total is: " + parallelSum.parallelSum(nums));
System.out.println("Execution time in milliseconds: " + (System.currentTimeMillis() - start));
}
}
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Random;
public class parallel {
public static void main(String[] args) {
Random rand = new Random();
int[] arr=new int[10];
for (int i = 0; i < arr.length; i++){
arr[i]=rand.nextInt();
//System.out.println();
}
long start = System.currentTimeMillis();
System.out.println("Total: "+A.parallelexec(arr));
long end = System.currentTimeMillis();
System.out.println("Total Execution Time in Milisecond: " + (end-start));
}
}
class A extends Thread{
private int[] arr;
private int low, high, partial;
public A(int[] arr, int low, int high)
{
this.arr = arr;
this.low = low;
this.high = Math.min(high, arr.length);
}
public int getPartial()
{
return partial;
}
public void run()
{
partial = sum(arr);
}
public static int sum(int[] arr)
{
int low=0;
int high=arr.length;
int total = 0;
for (int i = low; i < high; i++) {
total += arr[i];
}
return total;
}
public static int parallelexec(int[] arr)
{
return parallelexec(arr, Runtime.getRuntime().availableProcessors());
}
public static int parallelexec(int[] arr, int threads)
{
int size = (int) Math.ceil(arr.length * 1.0 / threads);
A[] sums = new A[threads];
for (int i = 0; i < threads; i++) {
sums[i] = new A(arr, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (A sum : sums) {
sum.join();
}
} catch (InterruptedException e) { }
int total = 0;
for (A sum : sums) {
total += sum.getPartial();
}
return total;
}
}
package com.company;
import java.util.Random;
public class Parallel extends Thread {
private int[] nums;
private int low;
private int high;
private int partialSum;
public Parallel(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
public int getPartialSum() {
return partialSum;
}
@Override
public void run() {
partialSum = 0;
for (int i = low; i < high; i++) {
partialSum += nums[i];
}
}
}
class ParallelSum {
private Parallel[] sums;
private int numOfThreads;
public ParallelSum(int numOfThreads) {
this.sums = new Parallel[numOfThreads];
this.numOfThreads = numOfThreads;
}
public int parallelSum(int[] nums) {
int size = (int) Math.ceil(nums.length * 1.0 / numOfThreads);
for (int i = 0; i < numOfThreads; i++) {
sums[i] = new Parallel(nums, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (Parallel sum : sums) {
sum.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int total = 0;
for (Parallel sum : sums) {
total += sum.getPartialSum();
}
return total;
}
}
class TestParallel {
public static void main(String[] args) {
Random random = new Random();
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int[] nums = new int[11];
System.out.print("10 random numbers are ");
for (int i = 1; i < nums.length; i++) {
nums[i] = random.nextInt(10);
System.out.print(nums[i]+" ");
}
long start = System.currentTimeMillis();
ParallelSum parallelSum = new ParallelSum(numOfProcessors);
System.out.println("\nTotal is: " + parallelSum.parallelSum(nums));
System.out.println("Execution time in milliseconds: " + (System.currentTimeMillis() - start));
}
}
package test01;
import java.util.Random;
public class ran {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int numOfProcessors = Runtime.getRuntime().availableProcessors();
int numbers[] = new int[10];
Random random = new Random();
for(int i = 0; i < 10; i++){
int num = random.nextInt();
numbers[i] = num;
}
Sum ps = new Sum(numOfProcessors);
System.out.println("Total : " + ps.Sum(numbers));
long end = System.currentTimeMillis();
System.out.println("Time taken in milliseconds : " +(end-start) );
for(int j = 0;j<numbers.length;j++){
System.out.println("number is: "+numbers[j]);
}
System.out.println("Their are "+numbers.length+" numbers.");
}
}
class Sum {
private worker[] sums;
private int numOfThreads;
public Sum(int numOfThreads) {
this.sums = new worker[numOfThreads];
this.numOfThreads = numOfThreads;
}
public int Sum(int[] nums) {
int size = (int) Math.ceil(nums.length * 1.0 / numOfThreads);
for (int i = 0; i < numOfThreads; i++) {
sums[i] = new worker(nums, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (worker sum : sums) {
sum.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int total = 0;
for (worker sum : sums) {
total += sum.getSum();
}
return total;
}
}
class worker extends Thread {
private int[] nums;
private int low;
private int high;
private int Sum;
public worker(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
public int getSum() {
return Sum;
}
@Override
public void run() {
Sum = 0;
for (int i = low; i < high; i++) {
Sum += nums[i];
}
}
}
Class Parallel
package com.baktajivan.parallel;
public class Parallel{
public static int parasum(int[] arr, int threads) {
int threadSize = (int) Math.ceil(arr.length*1.0 /threads);//divide threads into available proceeesor
ParMethod [] parsum = new ParMethod[threads];//create array with length of thread available
//to create thread
for(int i=0; i< threads;i++){
parsum[i] = new ParMethod(arr,i*threadSize,(i+1)*threadSize);
parsum[i].start();
}//for loop start thread
try{
for (ParMethod par : parsum){
par.join();
}
}catch (InterruptedException e){
e.printStackTrace();
}//try join thread
int total = 0;
for (ParMethod par: parsum){
total+= par.getPartialSum();
}//
return total;
}
}
Class ParMethod
package com.baktajivan.parallel;
public class ParMethod extends Thread {
private int low;
private int high;
private final int[] arr;
private int partialSum;
public ParMethod(int[] arr, int first, int second) {
this.low = first;
this.high = Math.min(second,arr.length);
this.arr = arr;
}
public int getPartialSum() {
return partialSum;
}
@Override
public void run() {
partialSum =0;
for (int i = low; i<high; i++){
partialSum += arr[i];
}
}
}
Class Main
package com.baktajivan.parallel;
import com.baktajivan.sequential.Sequential;
import java.util.Random;
public class Main {
public static void main(String [] args){
Random random = new Random();
Sequential sequential = new Sequential();
int processor = Runtime.getRuntime().availableProcessors();
int [] arr = new int [10];
for (int i = 0; i < arr.length; i++){
arr[i] =random.nextInt(10)+1;
//System.out.println(arr[i]);
}//for loop to generate and print random numbers
/*long start = System.currentTimeMillis();
System.out.println("Total is: "+sequential.sum(arr));
System.out.println("Single: "+(System.currentTimeMillis() - start) + "ms");*/
long start = System.currentTimeMillis();
Parallel parasum = new Parallel();
System.out.println("Total is: "+ Parallel.parasum(arr,processor));
System.out.println("Parallel: " +(System.currentTimeMillis() -start) + "ms");
}
}
Output:
Reference: https://eddmann.com/posts/parallel-summation-in-java/ https://github.com/zhamri/STIW3054-RT-Programming/tree/master/src/Week_13
import java.util.Random;
import java.util.Scanner;
class Main extends Random {
private static Scanner sc = new Scanner(System.in);
private static int[] i1;
public static void main(String[] args) {
randomParallel parallel = new randomParallel();
System.out.print("Enter how many random numbers need to be sum: ");
int num = sc.nextInt();
i1 = new int[num];
parallel.setNum(num);
System.out.println();
System.out.println("Parallel Sum");
Thread thread = new randomParallel();
thread.start();
}
static class randomParallel extends Thread{
static int num;
static Random random = new Random();
void setNum(int num) {
synchronized (this) {
randomParallel.num = num;
}
}
public void run() {
long l = System.currentTimeMillis();
for (int i = 0; i < num; i++) {
i1[i] = random.nextInt(100);
new plus(i1[i]);
if (i == num - 1) {
System.out.print(i1[i] + " = ");
} else {
System.out.print(i1[i] + " + ");
}
}
long l1 = System.currentTimeMillis();
System.out.println(plus.aDouble);
System.out.println("Time taken: " + (l1 - l) + "ms");
}
}
static class plus {
static int aDouble;
plus(int i) {
aDouble += i;
}
}
}
package issues_12;
import static java.lang.Thread.sleep;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Ahmed_Bawazir
*/
public class ParallelSum {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException {
// TODO code application logic here
Mythread1 Th = new Mythread1();
Thread t1 = new Thread (Th);
t1.start();
}
}
class Mythread1 implements Runnable {
@Override
public void run() {
Random r = new Random();
long startTime = System.nanoTime();
int j = 0, sum = 0;
for (int i = 1; i <= 10; i++) {
j = r.nextInt(10);
try {
TimeUnit.SECONDS.sleep((long) 0.1);
} catch (InterruptedException e) {}
sum = sum + j;
System.out.println("Number:"+i+" = "+j);
}
System.out.println("Sum All Numbers = " + sum);
long endTime = System.nanoTime();
long timeElapsed = endTime - startTime;
System.out.println("Execution time in milliseconds: " + timeElapsed / 1000000);
}
}
import java.util.Random;
public class parallelSum{
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Random objGenerator = new Random();
for (int iCount = 0; iCount< 10; iCount++){
int randomNumber = objGenerator.nextInt(100);
System.out.println("Random No : " + randomNumber);
}
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println("\nExecution time in milliseconds: " + timeElapsed);
}
}
import java.util.Random;
import java.util.Scanner;
class one extends Random {
private static Scanner sc = new Scanner(System.in);
private static int[] i1;
public static void main(String[] args) {
randomParallel parallel = new randomParallel();
System.out.print("Enter how many random numbers need to be sum: ");
int num = sc.nextInt();
i1 = new int[num];
parallel.setNum(num);
System.out.println();
System.out.println("Parallel Sum");
Thread thread = new randomParallel();
thread.start();
}
static class randomParallel extends Thread{
static int num;
static Random random = new Random();
void setNum(int num) {
synchronized (this) {
randomParallel.num = num;
}
}
public void run() {
long l = System.currentTimeMillis();
for (int i = 0; i < num; i++) {
i1[i] = random.nextInt(100);
new plus(i1[i]);
if (i == num - 1) {
System.out.print(i1[i] + " = ");
} else {
System.out.print(i1[i] + " + ");
}
}
long l1 = System.currentTimeMillis();
System.out.println(plus.aDouble);
System.out.println("Time taken: " + (l1 - l) + "ms");
}
}
static class plus {
static int aDouble;
plus(int i) {
aDouble += i;
}
}
}
import java.util.*;
public class Birthday {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int numbers[] = new int[10];
int total =0;
System.out.println("Generated numbers are: ");
for (int i = 0; i < 10; i++) {
System.out.printf (" "+ gen_rand()+" + ");
numbers[i]= gen_rand();
total = total +numbers[i];
}
System.out.println("Total : "+total);
long end = System.currentTimeMillis();
System.out.println("Time taken in milliseconds : " + (end-start));
}
public static int gen_rand (){
Random rand = new Random();
int num = rand.nextInt(100);
return num;
}
}
Instruction
Write a Java program to sum 10 random numbers using parallel execution. Then calculate the execution time in milliseconds.
Submission
Java code Screenshot of the output