title: java.util.concurrent : calculating primes
body: <p>I'm new to the package <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html" rel="nofollow noreferrer">java.util.concurrent</a>. I've created the following program testing if a number is a prime using a multi and a monothreaded strategy.</p>
  
  <pre><code>import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  
  
  public class IsPrime
          implements Runnable
      {
      private static final long UPPER_BOUND=100000;
      long value;//the number observed
      private IsPrime(long value)
          {
          this.value=value;
          }
      /** returns wether value is a prime number (simple and stupid method ) */
      private boolean isAPrimeNumber()
          {
          if(value==1 || value==2) return true;
          if(value%2L==0) return false;
          for(long i=3;i&lt; value;++i)
              {
              if(this.value%i==0) return false;
              }
          return true;
          }
  
      @Override
      /** calls isAPrimeNumber */
      public void run()
          {
          boolean result=isAPrimeNumber();
          //if(result) System.out.println("["+this.value+"]");
          }
  
      /** loop from 3 to UPPER_BOUND, multithreaded */
      private static long loopMT() 
          {
          long now=System.currentTimeMillis();
          ExecutorService service=Executors.newFixedThreadPool(10); 
  
          for(long i=3;i&lt; UPPER_BOUND;i+=2)
              {
              service.submit(new IsPrime(i));
              }
          service.shutdown();
          return System.currentTimeMillis()-now;
          }
  
      /** loop from 3 to UPPER_BOUND, NOT multithreaded */
      private static long loop() 
          {
          long now=System.currentTimeMillis();
          for(long i=3;i&lt; UPPER_BOUND;i+=2)
              {
              new IsPrime(i).run();
              }
          return System.currentTimeMillis()-now;
          }
  
      public static void main(String[] args)
          {
          long n1=IsPrime.loop();
          long n2=IsPrime.loopMT();
          System.out.println(""+n1+" &gt;&gt;&gt; "+n2);   
          }
      }
  </code></pre>
  
  <p>for the method <strong>loopMT</strong>, is it the correct way to use the classes of the package <strong>java.util.concurrent</strong> ? Is there another, (safer, more elegant) way to write this program ? Can I use System.out in a multithreaded environement ?</p>
  
  <p>Many thanks for your suggestions</p>
  
  <p>Pierre</p>