Skip to content

Instantly share code, notes, and snippets.

@samkeeleyong
Last active August 31, 2015 10:14
Show Gist options
  • Save samkeeleyong/5b79524ef2668177047d to your computer and use it in GitHub Desktop.
Save samkeeleyong/5b79524ef2668177047d to your computer and use it in GitHub Desktop.
MSCS-OS-assignment1
import java.util.*;
import java.lang.IllegalStateException;
/**
* @author Sam Ong
*
*/
public class PrimeAssignment {
static boolean IS_COMPOSITE = false;
private static List<ThreadMeta> metaList = new ArrayList<>();
public static void main(String[] args) throws InterruptedException{
int number = 465321,
numberOfThreads = 3;
ThreadMeta.number = number;
//setup
delegateThreads(number, numberOfThreads);
for(ThreadMeta meta: metaList){
Thread thread = new Thread(new PrimeLooper(meta));
meta.thread = thread;
thread.start();
}
for(ThreadMeta meta: metaList){
meta.thread.join();
}
// After all the threads finish
System.out.printf("%d is %s\n", number, IS_COMPOSITE ? "composite":
"prime");
for(ThreadMeta meta: metaList){
System.out.printf("\n%s's last processed number is %d", meta.thread.getName(), meta.lastProcessedNumber);
}
}
/*
* divides the number by numberOfThreads
* e.g. 17 maybe divided into 3 with
* [3 - 7], [7 - 11], [11 - 17]
*/
public static void delegateThreads(int number, int numberOfThreads){
int start = 3,
end = (int)(Math.ceil(Math.sqrt(number)));
// if(numberOfThreads > end){ nagloloko computer ko, windows kasi
// throw java.lang.IllegalStateException("Number of Threads too big!");
// }
int total_length = end - start;
int subrange_length = (int) (Math.ceil((total_length / numberOfThreads)));
int current_start = start;
for (int i = 1; i <= numberOfThreads; ++i) {
ThreadMeta meta = new ThreadMeta();
meta.start = current_start % 2 == 0 ? current_start - 1:
current_start;
meta.end = (current_start + subrange_length);
metaList.add(meta);
current_start += subrange_length + 1;
}
// hack because i've spent too much time already.
metaList.get(metaList.size() - 1).end = end;
System.out.println("Ranges of the threads:" + metaList);
}
}
/*
* This is the Thread
*/
class PrimeLooper implements Runnable{
public void run(){
if(ThreadMeta.number % 2 == 0){
meta.lastProcessedNumber = 2;
System.out.printf("%d is divisible by %d\n", ThreadMeta.number, 2);
PrimeAssignment.IS_COMPOSITE = true;
}
// e.g. 1 - 1000 or 2 - 1000
for(int i = meta.start; i <= meta.end && !PrimeAssignment.IS_COMPOSITE; i+=2){
meta.lastProcessedNumber = i;
if(ThreadMeta.number % i == 0){
System.out.printf("%d is divisible by %d\n", ThreadMeta.number, i);
PrimeAssignment.IS_COMPOSITE = true;
}
}
}
ThreadMeta meta;
PrimeLooper(ThreadMeta meta){
this.meta = meta;
}
}
class ThreadMeta{
int start;
int end;
Thread thread;
static int number;
int lastProcessedNumber;
public String toString(){
return String.format("[%d - %d]", start, end);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment