title: How to make a thread limit in Java
body: <p>Let's say I have 1000 files to read and because of some limits, I want to read maximum 5 files in parallel. And, as soon as one of them is finished, I want a new one starts.</p>
  
  <p>I have a main function who have the list of the files and I try changing a counter whenever one thread is finished. but it doesn't works!</p>
  
  <p>Any suggestion?</p>
  
  <p>The following is the main function loop</p>
  
  <pre><code>for (final File filename : folder.listFiles()) {
  
      Object lock1 = new Object();
      new myThread(filename, lock1).start();
      counter++;
      while (counter &gt; 5);
  }
  </code></pre>