С черновой отладкой (печатает) я показываю, что каждый поток возвращает свою частичную сумму с ценой 500. Например, 8 потоков * 500, его 4000 -> 4,0000 вычислений числа пи, я думаю, что это проблема с myStart и myStop ... ты можешь помочь? Здесь я даю свои классы:
ThreadParArray:
class ThreadParArray
{
public static void main(String[] args)
{
int numThreads = 0;
long numSteps = 1000;
// if (args.length != 2) {
// System.out.println("Usage: java ThreadParSqrt <vector size> <number of threads>");
// System.exit(1);
// }
//
// try {
// size = Integer.parseInt(args[0]);
// numThreads = Integer.parseInt(args[1]);
// }
// catch (NumberFormatException nfe) {
// System.out.println("Integer argument expected");
// System.exit(1);
// }
if (numThreads == 0) numThreads = Runtime.getRuntime().availableProcessors();
double[] tsum = new double[numThreads];
for(int i = 0; i < numThreads; i++)
tsum[i] = 0.0;
// get current time
long startTime = System.currentTimeMillis();
// create threads
NumIntThread threads[] = new NumIntThread[numThreads];
// thread execution
for (int i = 0; i < numThreads; i++)
{
threads[i] = new NumIntThread(i, numThreads, tsum, numSteps);
threads[i].start();
}
// wait for threads to terminate
for (int i = 0; i < numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {}
}
double sum = 0.0;
for (int i = 0; i < numThreads; i++) {
sum = sum + tsum[i];
}
double step = 1.0 / (double)numSteps;
double pi = sum*step;
/* end timing and print result */
long endTime = System.currentTimeMillis();
System.out.printf("sequential program results with %d steps\n", numSteps);
System.out.printf("computed pi = %22.20f\n" , pi);
System.out.printf("difference between estimated pi and Math.PI = %22.20f\n", Math.abs(pi - Math.PI));
System.out.printf("time to compute = %f seconds\n", (double) (endTime - startTime) / 1000);
}
}
NumIntThread
class NumIntThread extends Thread
{
private double [] sums;
private int myId;
private long myStart;
private long myStop;
private double step;
// constructor
public NumIntThread(int id, int numThreads, double[] ts, long steps)
{
sums = ts;
myId = id;
myStart = (myId * (steps / numThreads));
myStop =(myStart + (steps / numThreads));
if (myId == (numThreads - 1)) myStop =steps;
double step = 1.0 / (double)steps;
}
// thread code
public void run()
{
for(long i = myStart; i < myStop; ++i) {
double x = ((double)i+0.5)*step;
sums[myId] += 4.0/(1.0+x*x);
}
}
}
Ps Я новичок ie но я стараюсь изо всех сил