Created
July 28, 2012 05:39
-
-
Save xstherrera1987/3191952 to your computer and use it in GitHub Desktop.
computing prime numbers in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<project default="cmp"> | |
<target name="cmp"><javac srcdir="." debug="true"/></target> | |
<target name="run" depends="cmp"><java classname="Main" classpath="."/></target> | |
<target name="cln"><delete><fileset dir="." includes="*.class"/></delete></target> | |
</project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class Main { | |
static final int MAX = 100000; | |
static final int THREADS = Runtime.getRuntime().availableProcessors(); | |
static final int ARRINITSIZE = 100000; | |
static ArrayList<Integer> primes = new ArrayList<Integer>(ARRINITSIZE); | |
public static void main(String[] args) throws Exception { | |
Thread[] t = new Thread[THREADS]; | |
PrimeRun.m = new Monitor(); | |
for (int i=0; i<THREADS; i++) { | |
t[i] = new Thread(new PrimeRun(i) ); | |
t[i].start(); | |
} | |
// wait for threads to finish | |
for (int i=0; i<THREADS; i++) | |
t[i].join(); | |
// print out all primes | |
// NOTE: they will be out of order because of random thread scheduling | |
for (int n : primes) | |
System.out.print("" + n + " "); | |
System.out.println(); | |
} | |
public static boolean isPrime(int n) { | |
if (n == 2 || n == 3 || n == 5) return true; | |
if (n <= 1 || (n&1) == 0) return false; | |
for (int i = 3; i*i <= n; i += 2) | |
if (n % i == 0) return false; | |
return true; | |
} | |
public synchronized static void addPrime(int n) { | |
primes.add(n); | |
} | |
} | |
class PrimeRun implements Runnable { | |
public static Monitor m; | |
final int ID; | |
public PrimeRun(int i) { | |
ID = i; | |
} | |
public void run() { | |
for(int i=0; i < Main.MAX; i++) { | |
if(i % Main.THREADS == ID) | |
if(Main.isPrime(i)) | |
m.addPrime(i); | |
} | |
} | |
} | |
class Monitor { | |
public synchronized void addPrime(int n) { | |
Main.addPrime(n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment