对于一个分配,我必须实现一个Java程序,当它与多个线程一起运行实际上比只有1时慢。我知道创建线程需要一些开销,但在本例中我正在处理20,000 x 20,000的大数组。没有依赖关系,所以创建4个较小的块并同时运行它们的好处应该始终超出创建线程的成本吗?什么时候1个线程的运行速度会比多个线程同时运行的要快
for (int i = 0; i < numThreads; i++) {
// for each iteration of the body's for loop,
// calculate the starting and ending indexes
// of the ith chunk of the y dimension of
// the anArray array
final int indexStart = i * chunkSize;
final int indexEnd = (i + 1) * chunkSize;
// each "execute" method of the Executor class
// creates a new object of type Runnable ...
// be careful with the parentheses here ... the
// entire next code block is being passes
// as a parameter to the execute method
ex.execute(new Runnable() {
// The run() method is declared abstract in the Runnable
// class, so it MUST be overriden. The body of the
// run method is the "code" that each thread executes
@Override
public void run() {
for (int j=0; j<anArray.length; j++){
for (int k = indexStart; k < indexEnd; k++){
anArray[j][k] = anArray[j][k] * anArray[j][k]/3.45 * Math.sqrt(anArray[j][k]);
}
} // end for
} // end run
}
);
}
我们的任务是修改只有最里面的循环中,我们可以做什么都希望我们在那里,但它有当多个线程执行,使运行速度较慢。具有8个线程的上限。 我真正的问题是在实现多个线程时可能导致更多的问题。我已经做了一些研究,发现你可以使用单线程来使用大多数的CPU,所以创建更多不会帮助,这怎么可能。
是否有可以创建的线程数的上限?如果没有,那么你可以在每次迭代(或其混合)上创建一个线程。 – txtechhelp
应该是一个8的上限 – user3267256
你说'*它必须使运行时运行速度较慢,执行时少线程*'。而你的头衔似乎相反......你想要什么? – smwikipedia