Add numbers using 5 threads
Solution 1
here is the problem:
sum = sum + a;
it should be sum += i;
BTW, you don't need any synchronization here
if you want delay between additions - use Thread.sleep(1000L);
Solution 2
As per Lashane, there is no need to synchronize here - there is no contention on sum
as each thread will have its own variable. (And if you do need to synchronize, don't synchronize on this
as the object reference has scope outside of the class and could e.g. be subject to deadlock - instead, synchronize on a private field object, e.g. private final Object lock = new Object();
)
public void add(int a, int b){
int sum=0;
for(int i=a;i<=b;i++){
sum = sum + i;
Thread.sleep(1000);
}
System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);
}
Also, after starting threads, you will need to join them back into the main thread.
...
t4.start();
t5.start();
// Join
t1.join();
t2.join();
...
Solution 3
Add Thread.sleep(1000L)
to your add method
public void add(int a, int b) throws InterruptedException {
int sum=0;
synchronized (this) {
for(int i=a;i<=b;i++){
sum += i;
Thread.sleep(1000L); // Add this line for one second delay on each addition
}
System.out.println("Sum of "+a+" to "+ b+" numbers = "+sum);
}
}
UserJS
Updated on June 18, 2022Comments
-
UserJS almost 2 years
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