I was challenged by my professor to write the program in Java for the following prompt: "Suppose we would like to find the sum of the integers within the range [1, 100]. Create four threads and each thread calculates the sum of 25 integers. Print out the overall sum and the program running time. Thread1: [1, 25], Thread2: [26, 50], Thread3: [51, 75], and Thread4: [76,100]."
I was able to complete the following, however, the totalTime is printing sometimes first, sometimes second, etc. I'd like it to print at the end, is this possible? Also, why is this happening? Thank you for your time!
My current code:
public class ThreadAdding
{
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
Thread t1 = new Thread(new addition(1,25));
Thread t2 = new Thread(new addition(26,50));
Thread t3 = new Thread(new addition(51,75));
Thread t4 = new Thread(new addition(76,100));
t1.start();
t2.start();
t3.start();
t4.start();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Total time for operations: " + totalTime);
}
}
class addition implements Runnable
{
int a,b;
public addition(int a, int b)
{
this.a = a;
this.b = b;
}
public void run()
{
add(a,b);
}
public void add(int a, int b)
{
int sum = 0;
synchronized (this)
{
for(int i = a; i <= b; i++)
{
sum += i;
}
System.out.println("Sum of numbers from " + a + " to " + b + " = " + sum);
}
}
}