Skip to content
Snippets Groups Projects
Commit ac2375d2 authored by Jean-Marie Place's avatar Jean-Marie Place
Browse files

initial commit

parents
Branches master
No related tags found
No related merge requests found
package threads;
public class FastFiller {
class PartialFiller extends Thread {
double[] t;
int no;
int from;
int to;
public PartialFiller(int no, double[] t, int from, int to) {
this.t = t;
this.no = no;
this.from = from;
this.to = to;
}
@Override
public void run() {
for (int i = from; i < to; i++) {
t[i] = Math.sin(i + 0.0);
}
System.out.print(no + " done.");
}
}
private final int nbThreads;
public FastFiller(int nbThreads) {
this.nbThreads = nbThreads;
}
public void fill(double[] t) {
Thread[] threads;
int[] ranges = new int[nbThreads];
threads = new Thread[nbThreads];
int rangeSize = t.length / nbThreads;
ranges[ranges.length-1] = t.length;
int bound = 0;
for (int i = 1; i < nbThreads; i++) {
int nextBound = bound + rangeSize;
threads[i] = new PartialFiller(i, t, bound, nextBound);
bound = nextBound;
}
threads[0] = new PartialFiller(nbThreads, t, bound, t.length);
for (int i = 0; i < nbThreads; i++) {
threads[i].start();
}
for(int i = 0; i < nbThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
}
package threads;
public class Filler {
public void fill(double[] t) {
for (int i = 0; i < t.length; i++) {
t[i] = Math.sin(i);
}
}
}
package threads;
public class Main {
public static void main(String[] args) {
double[] t = new double[200000000];
Filler f = new Filler();
long t0;
t0 = System.currentTimeMillis();
f.fill(t);
System.out.println("no thread\t" + (System.currentTimeMillis() - t0));
for (int nbt = 1; nbt < 20; nbt++) {
FastFiller ff = new FastFiller(nbt);
t0 = System.currentTimeMillis();
ff.fill(t);
System.out.println(nbt + "\t" + (System.currentTimeMillis() - t0));
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment