【发布时间】:2013-09-13 12:47:08
【问题描述】:
我有一个可能是一个基本问题。当我在单核上创建 1 亿个哈希表时,我的机器上大约需要 6 秒(运行时间 = 每个核心 6 秒)。如果我在 12 个内核上执行此多线程(我的机器有 6 个允许超线程的内核),则大约需要 10 秒(运行时间 = 每个内核 112 秒)。
这是我使用的代码:
主要
public class Tests
{
public static void main(String args[])
{
double start = System.currentTimeMillis();
int nThreads = 12;
double[] runTime = new double[nThreads];
TestsThread[] threads = new TestsThread[nThreads];
int totalJob = 100000000;
int jobsize = totalJob/nThreads;
for(int i = 0; i < threads.length; i++)
{
threads[i] = new TestsThread(jobsize,runTime, i);
threads[i].start();
}
waitThreads(threads);
for(int i = 0; i < runTime.length; i++)
{
System.out.println("Runtime thread:" + i + " = " + (runTime[i]/1000000) + "ms");
}
double end = System.currentTimeMillis();
System.out.println("Total runtime = " + (end-start) + " ms");
}
private static void waitThreads(TestsThread[] threads)
{
for(int i = 0; i < threads.length; i++)
{
while(threads[i].finished == false)//keep waiting untill the thread is done
{
//System.out.println("waiting on thread:" + i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
线程
import java.util.HashMap;
import java.util.Map;
public class TestsThread extends Thread
{
int jobSize = 0;
double[] runTime;
boolean finished;
int threadNumber;
TestsThread(int job, double[] runTime, int threadNumber)
{
this.finished = false;
this.jobSize = job;
this.runTime = runTime;
this.threadNumber = threadNumber;
}
public void run()
{
double start = System.nanoTime();
for(int l = 0; l < jobSize ; l++)
{
double[] test = new double[65];
}
double end = System.nanoTime();
double difference = end-start;
runTime[threadNumber] += difference;
this.finished = true;
}
}
我不明白为什么在多个线程中同时创建对象每个线程需要更长的时间,然后只在 1 个线程中串行执行。如果我删除创建哈希表的行,这个问题就会消失。如果有人能帮我解决这个问题,我将不胜感激。
【问题讨论】:
-
我想说创建 100,000,000 个哈希表是个问题。
-
应用程序实际上是在使用多核吗?如果它不跨越内核并且不得不关闭线程,我可以看到它需要更长的时间,因为那样你就会有这样的开销。
-
当您删除哈希表创建时,您的线程什么也不做,所以没有什么可比较的;0
-
你对
runtime变量的使用让我有点害怕。 -
@Bobby 它应该会吓到你,因为它涉及数据竞赛。这种代码的所有读数都是毫无价值的。
标签: java multithreading