title: Divide Loop Execution According to Threads In Java
body: <p>suppose i have a method <strong>run</strong> as following,   </p>
  
  <pre><code>public void run()
  {  
  for(i=loopstart;i&lt;loopend;i++){  
       //some code here to execute. no dependency exists   
  }   
  </code></pre>
  
  <p><strong>loopstart &amp; loopend</strong> variables have the min and max value of loop execution.</p>
  
  <p>now what i have to do is to divide this loop execution in 2 to 5 threads in order to execute in parallel. to accomplish this, i have changed this method as   </p>
  
  <pre><code>public void run()
  {
  for(i=thread_start; i&lt;thread_end; i++)
       //some code here to execute.    
  }
  </code></pre>
  
  <p>the variables <strong>thread_start</strong> and <strong>thread_end</strong> are the ranges each thread has to run. so how it would be best to divide loop execution. suppose i have the loop execution in the range  </p>
  
  <pre><code> 5-94   
  </code></pre>
  
  <p>and i want to divide it to many ranges for execution depending on number of threads.<br>
  e.g.    </p>
  
  <pre><code> threads               ranges    
   2                     5-44, 45-94   
   3                     5-34, 35-65, 66-94   
  </code></pre>
  
  <p>these are just examples (not exact). i want to divide its execution on the basis of threads available.<br>
  so for <strong>2 threads</strong>,     </p>
  
  <pre><code> thread_start=5  ,thread_end=44       1st thread 
   thread_start=45 ,thread_end=94       2nd thread.   
  </code></pre>
  
  <p>how should (using java code)  i divide loop execution in almost same length ranges?    </p>