
Write a Java program to create three theads. Each thread should produce the sum of 1 to 10, 11 to 20 and 21to 30 respectively. Main thread should wait for all the threads to be completed and it should be display final sum.

Java Thread Example
class ThreadExample{
static int sum,sum1,sum2,sum3;
public static void findsum() {
Runnable readRun1 = new Runnable() {
public void run() {
try{
Thread.sleep(1000);
for(int i=1;i<=10;i++){
sum1+=i;
}
//System.out.println(sum1);
} catch(Exception ex) {
}
}
};
Thread thread1 = new Thread(readRun1);
thread1.start();
Runnable readRun2 = new Runnable() {
public void run() {
try{
Thread.sleep(1000);
for(int i=11;i<=20;i++){
sum2+=i;
}
//System.out.println(sum2);
} catch(Exception ex) {
}
}
};
Thread thread2 = new Thread(readRun2);
thread2.start();
Runnable readRun3 = new Runnable() {
public void run() {
try{
Thread.sleep(1000);
for(int i=21;i<=30;i++){
sum3+=i;
}
//System.out.println(sum3);
} catch(Exception ex) {
}
}
};
Thread thread3 = new Thread(readRun3);
thread3.start();
Runnable main = new Runnable() {
public void run() {
try{
Thread.sleep(1000);
sum=sum1+sum2+sum3;
System.out.println("Result is: "+sum);
} catch(Exception ex) {
}
}
};
Thread mainth = new Thread(main);
mainth.start();
}
public static void main(String[] args)
{
ThreadExample.findsum();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.