Skip to main content

Threads using Runnable interface & java.lang.Thread.sleep method.(Calculate the sum of 1 to 5, 6 to 10 and 11 to 15)

Write a java program 1” at every 1000 Milliseconds and other should display “Thread 2” at every 3000 milliseconds to create 3 threads using Runnable interface. Three threads should calculate the sum of 1 to 5, 6 to 10 and 11 to 15 respectively. After all thread finishes main thread should print the sum and average.
CODING:
import java.lang.Thread;
class thread1 implements Runnable
{
 public void run(){
    try{
      System.out.println("Just Wait...");
      Thread.sleep(1000);
     }
    catch(Exception e){}
 }
}
class thread2 implements Runnable
{
 public void run(){
   try{
    System.out.println("Just Wait...");
    Thread.sleep(3000);
    }
   catch(Exception e){}
 }
}
class sum  implements Runnable {
  int sum=0,k;
  public sum (int start){k=start;}
  public void run(){
  for(int i=k-5;i<k;i++){sum=sum+i;}
  }
}
class ka{
 public static void main(String[] args){
    thread1 th1=new thread1();
    thread2 th2=new thread2();
    sum su1=new sum(6);
    sum su2=new sum(11);
    sum su3=new sum(16);
    Thread t1=new Thread(th1);
    Thread t2=new Thread(th2);
    Thread s1=new Thread(su1);
    Thread s2=new Thread(su2);
    Thread s3=new Thread(su3);
     t1.start();
     t2.start();
     s1.start();
     s2.start();
     s3.start();
      try{
           t1.join();
           t2.join();
           s1.join();
           s2.join();
           s3.join();
         }
     catch(Exception e) {}
   System.out.print("Sum : "+(su1.sum+su2.sum+su3.sum)+" Average : "+((su1.sum+su2.sum+su3.sum)/3));
  }
}

Comments