title: How to use multithreading in a loop in Java
body: <p>Here's what I'm trying to do. I am recording data from different sensors in a <code>while loop</code> until the user stops the recording. I want to record as much data as possible per second. The sensors require different time to return a value, between 200ms and 3 seconds. Therefore, sequentially calling the sensors successively is not an option. </p>
  
  <p>Sequentially calling the sensors looks like this:</p>
  
  <pre><code>List&lt;DataRow&gt; dataRows= new ArrayList&lt;DataRow&gt;();
  
  while (recording) {
     DataRow dataRow = new DataRow();
  
     dataRow.setDataA(sensorA.readData());
     dataRow.setDataB(sensorB.readData());
     dataRow.setDataC(sensorC.readData());
  
     dataRows.add(dataRow);
  }
  </code></pre>
  
  <p>Depending on the sensor, reading the data looks (much simplified) like that</p>
  
  <pre><code>public class SensorA {
  
     public SensorAData readData(){
        sensorA.startSensing();
  
        try {
            TimeUnit.MILLISECONDS.sleep(750);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); 
        }
  
        return sensorA.readAndConvertByteStream();
     }
  }
  </code></pre>
  
  <p>To utilize Multithreading can SensorA implement <code>Callable</code> and receive <code>Future</code> objects in the loop? Or should the <code>while loop</code> be placed within a <code>run()</code> method implementing the interface <code>Runnable</code>? </p>
  
  <p>Basically, can Java (or a thread) write to the correct <code>dataRow</code> object even if the loop is already at least one iteration further? If not, how can one solve this problem?</p>