Write a Program to add 1-100, 101-200, 201-300 in different threads and then sum the numbers ?
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

 Q1. Write a Program to add 1-100, 101-200, 201-300 in different threads and then sum the numbers ?Core Java
Ans. public class TotalUsingThreads extends Thread{
   
   private static List<TotalUsingThreads> collector = new ArrayList<TotalUsingThreads>();
   
   private int startFrom = 0;
   
   private Integer threadTotal = null;
   
   Test(int startFrom){
      this.startFrom = startFrom;
   }
   
   
   public static void main(String[] args) throws InterruptedException{
      int totalSum = 0;
      
      // Create all the threads and set the count starting point for all of them
      for(int count=0;count<10;count++){
         TotalUsingThreads newThread = new TotalUsingThreads(count*100);
         newThread.start();
         collector.add(newThread);
      }
      
      boolean allCollected = false;
      
      
      // Make sure that all thread totals are collected and all threads have completed their tasks
      while(!allCollected){
         for(int count=0;count<10;count++){
            if(collector.get(count).threadTotal == null){
               Thread.sleep(100);
               break;
            }
         }
         allCollected = true;
      }
      
      // sum totals of all threads
      for(int count=0;count<10;count++){
         totalSum += collector.get(count).threadTotal;
      }
      
      System.out.println(totalSum);
      
      
   }
   
   public void run(){
      threadTotal = 0;
      for(int count=startFrom;count<startFrom+100;count++){
       threadTotal += count;   
      }
   }
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     coding  code  threads  multithreading     Asked in 1 Companies


Related Questions

  What are the steps to be performed while coding Junit with Mocking framework ?
  What is a Sequence File?
 What different level of logging you use while coding ?
 Have you ever encoded the response before sending it back from the service? If Yes , Which encoding was used ?
 What are the different type of encoding you have used ?
 How does encoding affect using Reader / writer classes or Stream classes in Java ?
 What is the difference between html encoding and url encoding ?
 Does spaces get's encoded in html encoding ?



Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: