Skip to content

Instantly share code, notes, and snippets.

@sreid8
Last active December 20, 2015 15:09
Show Gist options
  • Save sreid8/902de98e043c9e0e7555 to your computer and use it in GitHub Desktop.
Save sreid8/902de98e043c9e0e7555 to your computer and use it in GitHub Desktop.
Example of multithreading from a reddit question
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Entropy {
public static void main(String[] args) {
}
private double log(double num, int base){
return Math.log(num)/Math.log(base);
}
public double entropy(List<String> data){
double entropy = 0;
ArrayList<EntropyCalculator> calcs = new ArrayList<EntropyCalculator>();
int numProcessors = Runtime.getRuntime().availableProcessors();
for (int i = 0; i < numProcessors; i++)
{
calcs.add(new EntropyCalculator());
}
int j = 0;
for (int i = 0; i < data.size(); i++) {
calcs.get(j).addData(data.get(i));
if (j == calcs.size() - 1) {
j = 0;
} else {
j++;
}
}
for (int i = 0; i < calcs.size(); i++) {
calcs.get(i).run();
}
//we just wait for one of them because the rest shouldn't be far behind.
while (calcs.get(0).isRunning()) {
try {
//100 ms sleep while we wait, this could be optimized
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < calcs.size(); i++) {
//check my math, you may want to use another way to combine results
entropy += calcs.get(i).getResult();
}
return entropy;
}
private class EntropyCalculator implements Runnable {
private double result = 0;
private List<String> data = Collections.emptyList();
private boolean running = false;
public void run() {
running = true;
double entropy = 0.0;
double prob = 0.0;
if(this.iFrequency.getKeys().length==0){
this.setInterestedFrequency(data);
}
String[] keys = iFrequency.getKeys();
for(int i=0;i<keys.length;i++){
prob = iFrequency.getPct(keys[i]);
entropy = entropy - prob * log(prob,2);
}
iFrequency.clear();
result = entropy;
running = false;
}
public double getResult() {
return result;
}
public void addData(String data) {
this.data.add(data);
}
public boolean isRunning() {
return running;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment