【发布时间】:2014-03-31 19:19:22
【问题描述】:
目前我的代码一个接一个地为多个核心实例化一个类,但我想创建一个循环,为任意数量的核心实例化类检测器(),同时运行。
int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads
detectors.getStartingConditions();
long startTime = System.currentTimeMillis();
detectors core1= new detectors();
detectors core2= new detectors();
detectors core3= new detectors();
//etc
core1.start();
core2.start();
core3.start();
//etc
try
{ // wait for completion of all thread and then sum
core1.join();
core2.join();
core3.join();
//etc
}
catch(InterruptedException IntExp) {}
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
我的解决方案尝试:
我创建了一个对象数组,如下所示,但处理器内核一个接一个地运行,而不是同时运行。
编辑:核心现在同时运行。
int processors = Runtime.getRuntime().availableProcessors(); // finds the number of available threads
detectors[] theCores = new detectors[processors];
detectors.getStartingConditions();
long startTime = System.currentTimeMillis();
for(int i = 0; i <= processors-1; i++){
theCores[i] = new detectors();
theCores[i].start();
}
for(int i = 0; i <= processors-1; i++){
try{
theCores[i].join();}
catch(InterruptedException IntExp) {}
}
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
【问题讨论】:
-
在创建进程 1 之前,您正在等待进程 0 的加入。
-
谢谢,我会更新帖子并进行更正 - 我认为现在代码可以正常工作,但如果您能检查一下,将不胜感激
标签: java multithreading loops object