Advertisement
Guest User

Untitled

a guest
Jul 28th, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. package org.dannil.mpt;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5.  
  6. public class Test {
  7.  
  8.     public Test() {
  9.  
  10.     }
  11.  
  12.     public void doOperation() {
  13.         int topBoundary = 10000000;
  14.  
  15.         double beforeMillis;
  16.         double afterMillis;
  17.  
  18.         System.out.println("Running in single-threaded mode");
  19.  
  20.         beforeMillis = System.currentTimeMillis();
  21.  
  22.         for (int i = 0; i < topBoundary; i++) {
  23.             Prime.isPrime(i);
  24.         }
  25.  
  26.         afterMillis = System.currentTimeMillis();
  27.  
  28.         System.out.println("Time elapsed: " + (afterMillis - beforeMillis) / 1000 + " sec.");
  29.  
  30.         System.gc();
  31.  
  32.         System.out.println("Running in multi-threaded mode");
  33.  
  34.         ExecutorService executor = Executors.newFixedThreadPool(4);
  35.  
  36.         beforeMillis = System.currentTimeMillis();
  37.  
  38.         for (int i = 0; i < topBoundary; i++) {
  39.             Runnable worker = new PrimeWorker(i);
  40.             executor.execute(worker);
  41.         }
  42.         executor.shutdown();
  43.  
  44.         afterMillis = System.currentTimeMillis();
  45.  
  46.         System.out.println("Time elapsed: " + (afterMillis - beforeMillis) / 1000 + " sec.");
  47.     }
  48.  
  49.     class PrimeWorker implements Runnable {
  50.  
  51.         private int n;
  52.  
  53.         public PrimeWorker(int n) {
  54.             this.n = n;
  55.         }
  56.  
  57.         @Override
  58.         public void run() {
  59.             boolean isPrime = Prime.isPrime(this.n);
  60.             if (isPrime) {
  61.                 // System.out.println(this.n + " is a prime number!");
  62.             }
  63.         }
  64.  
  65.     }
  66.  
  67.     public static void main(String[] args) {
  68.         Test test = new Test();
  69.         test.doOperation();
  70.     }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement