おそらく基本的な質問があります。1 億個の Hashtable を作成する場合、シングル コアで作成した場合、私のマシンでは約 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 つのスレッドでシリアルに作成するよりも時間がかかる理由がわかりません。Hashtable を作成する行を削除すると、この問題はなくなります。誰かがこれで私を助けることができれば、私は非常に感謝しています.