Write a java program to create 3 threads using Thread class. Three threads should calculate the sum of 1 to 5, 6 to 10 and 11to 15 respectively. After all thread finishes main thread should print the sum and average.

 

AIM: Write a java program to create 3 threads using the Thread class. Three threads should calculate the sum of 1 to 5, 6 to 10, and 11to 15 respectively. After all the thread finishes main thread should print the sum and average.

CODE:

class MyThread1 extends Thread{

                        int sum = 0;

            public void run(){

                        for(int i=1;i<=5;i++){

                                    sum+=i;

                        }         

            }         

}

class MyThread2 extends Thread{

            int sum = 0;

            public void run(){

                        for(int i=6;i<=10;i++){

                                    sum+=i;

                        }         

            }         

}

class MyThread3 extends Thread{

            int sum = 0;

            public void run(){

                        for(int i=11;i<=15;i++){

                                    sum+=i;

                        }         

            }         

}

class threadMain3{

            public static void main(String args[]){

                        MyThread1 t1 = new MyThread1();

                        t1.start();

                        try{

                                    t1.join();

                        }

                        catch(Exception ep){

                        }

                        MyThread2 t2 = new MyThread2();

                        t2.start();

                        try{

                                    t2.join();

                        }

                        catch(Exception ep){

                        }

                        MyThread3 t3 = new MyThread3();

                        t3.start();

 

                        int sum = 0;

                        sum+=t1.sum;

                        sum+=t2.sum;

                        sum+=t3.sum;

                        System.out.println("\nSum of 1 to 15 is : "+sum);

                        float avg = 0;

                        avg = sum/15;

                        System.out.println("\nAverage of 1 to 15 is : "+avg);

            }

}

 

OUTPUT:


 

 

Comments

Popular posts from this blog

Write a program in Java to demonstrate single inheritance, multilevel inheritance and hierarchical inheritance.

Write a program in Java to demonstrate use of final class.