Question : I have to create 5 threads where each thread has to perform the addition operation.
- Thread1 - Add 1 to 10
- Thread2 - Add 1 to 50
- Thread3 - Add 5 to 15
- Thread4 - Add 10 to 20
- Thread5 - Add 15 to 20
What is the best way to accomplish this? Also, I need 1 sec time delay between each addition operation. I have written this code: My output is wrong and changing every time. I know problem is with synchronized but not able solve.
class adding implements Runnable{
int a,b;
public adding(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 = sum+ a;
}
System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);
}
}
}
public class addnumbersusing5threads {
public static void main(String[] args) {
Thread t1 = new Thread(new adding(1,10));
Thread t2 = new Thread(new adding(1,50));
Thread t3 = new Thread(new adding(5,15));
Thread t4 = new Thread(new adding(10,20));
Thread t5 = new Thread(new adding(15,20));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Output:
Sum of 1 to 10 numbers = 10
Sum of 1 to 50 numbers = 50
Sum of 5 to 15 numbers = 55
Sum of 10 to 20 numbers = 110
Sum of 15 to 20 numbers = 90