📄 bignums.java
字号:
//
//
// Cong Wang, 58211415
//
// CA670, Assessed Exercise 1, Standard Version
//
// My program performs as required by the problem specification.
//
// This is my own work. I have not received assistance beyond what is
// normal, and I have cited any sources from which I have borrowed. I
// have not given a copy of my work, or part of my work, to anyone.
// I am aware that copying or giving a copy may have serious
// consequences, including an outright fail for the module.
import java.util.*;
public class BigNums {
public static void main(String[] args) {
double[] list = new double[1 << 22];
for (int i = 0; i < list.length; i++)
list[i] = Math.random();
long startTime = System.nanoTime();
double[] bigs = bigNums(list);
long endTime = System.nanoTime();
System.out.println("Running time = " + ((endTime - startTime) / 1000));
System.out.println(bigs.length);
}
private static double[] bigNums(final double[] b) {
int numProc=Runtime.getRuntime().availableProcessors();
final int range=b.length/numProc;
Thread[] tt=new Thread[numProc];
//Calculation for the average
double sum=0;
final double[] sums=new double[numProc];
for(int i=0;i<numProc;i++)
{
final int lo=i*range;
final int ii=i;
tt[i]=new Thread(
new Runnable()
{
public void run()
{
for(int j=lo;j<Math.min(lo+range, b.length);j++)
{
sums[ii]+=b[j];
}
}
}
);
tt[i].start();
}
for(int k=0;k<numProc;k++)
{
try{tt[k].join();}catch(InterruptedException e){};
sum+=sums[k];
}
final double avr=sum/b.length;
//Pick up the bigs and place them in bigs[][]
final double[][] bigs=new double[numProc][range];
final int[] lens=new int[numProc];
int len=0;
for(int i=0;i<numProc;i++)
{
final int lo=i*range;
final int ii=i;
tt[i]=new Thread(
new Runnable()
{
public void run()
{
int len=0;
for(int j=lo;j<Math.min(lo+range, b.length);j++)
{
if(b[j]>avr) {bigs[ii][j-lo]=b[j];len++;}
}
lens[ii]=len;
}
}
);
tt[i].start();
}
for(int k=0;k<numProc;k++)
{
try{tt[k].join();}catch(InterruptedException e){};
len+=lens[k];
}
//merge the bigs[][] to bignums[]
double[] bignums=new double[len];
int pos=0;
for(int i=0;i<numProc;i++)
{
System.arraycopy(bigs[i], 0, bignums, pos, lens[i]);
pos+=lens[i];
}
return bignums;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -