我正在尝试实现的任务是使用多个线程在设置间隔中查找数字的Collatz序列,并查看与一个线程相比获得了多少改进。
然而,无论我选择2个线程,一个线程总是更快(编辑.2个线程更快,但不是很多,而4个线程比1个线程慢,我不知道为什么。(我甚至可以说线程越多)它越慢越好。我希望有人能解释。也许我做错了什么。
下面是我到目前为止编写的代码。我正在使用ThreadPoolExecutor来执行任务(一个任务=一个区间内一个数字的一个Collatz序列)。
Collatz课程:
public class ParallelCollatz implements Runnable {
private long result;
private long inputNum;
public long getResult() {
return result;
}
public void setResult(long result) {
this.result = result;
}
public long getInputNum() {
return inputNum;
}
public void setInputNum(long inputNum) {
this.inputNum = inputNum;
}
public void run() {
//System.out.println("number:" + inputNum);
//System.out.println("Thread:" + Thread.currentThread().getId());
//int j=0;
//if(Thread.currentThread().getId()==11) {
// ++j;
// System.out.println(j);
//}
long result = 1;
//main recursive computation
while (inputNum > 1) {
if (inputNum % 2 == 0) {
inputNum = inputNum / 2;
} else {
inputNum = inputNum * 3 + 1;
}
++result;
}
// try {
//Thread.sleep(10);
//} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
this.result=result;
return;
}
}
我运行线程的主类(是的,我现在创建两个具有相同数字的列表,因为在运行一个线程后,初始值丢失):
ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(1);
ThreadPoolExecutor executor2 = (ThreadPoolExecutor)Executors.newFixedThreadPool(4);
List<ParallelCollatz> tasks = new ArrayList<ParallelCollatz>();
for(int i=1; i<=1000000; i++) {
ParallelCollatz task = new ParallelCollatz();
task.setInputNum((long)(i+1000000));
tasks.add(task);
}
long startTime = System.nanoTime();
for(int i=0; i<1000000; i++) {
executor.execute(tasks.get(i));
}
executor.shutdown();
boolean tempFirst=false;
try {
tempFirst =executor.awaitTermination(5, TimeUnit.HOURS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("tempFirst " + tempFirst);
long endTime = System.nanoTime();
long durationInNano = endTime - startTime;
long durationInMillis = TimeUnit.NANOSECONDS.toMillis(durationInNano); //Total execution time in nano seconds
System.out.println("laikas " +durationInMillis);
List<ParallelCollatz> tasks2 = new ArrayList<ParallelCollatz>();
for(int i=1; i<=1000000; i++) {
ParallelCollatz task = new ParallelCollatz();
task.setInputNum((long)(i+1000000));
tasks2.add(task);
}
long startTime2 = System.nanoTime();
for(int i=0; i<1000000; i++) {
executor2.execute(tasks2.get(i));
}
executor2.shutdown();
boolean temp =false;
try {
temp=executor2.awaitTermination(5, TimeUnit.HOURS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("temp "+ temp);
long endTime2 = System.nanoTime();
long durationInNano2 = endTime2 - startTime2;
long durationInMillis2 = TimeUnit.NANOSECONDS.toMillis(durationInNano2); //Total execution time in nano seconds
System.out.println("laikas2 " +durationInMillis2);
例如,使用一个线程运行它在3280ms内完成。运行两个线程3437ms。我应该考虑另一个并发结构来计算每个元素吗?
编辑澄清。我不是试图并行化各个序列,而是每个数字都有序列时的数字间隔。(这与其他数字无关)
Aaditi
今天我在一台配备6个内核和12个逻辑处理器的PC上运行该程序,问题仍然存在。有谁知道问题可能在哪里?我还更新了我的代码。由于某种原因,4个线程比2个线程更差。(甚至比1个线程更差)。我也应用了答案中给出的内容,但没有变化。
另一个编辑我注意到如果我在我的ParallelCollatz方法中放入Thread.sleep(1),那么性能会随着线程数逐渐增加。也许这个细节告诉别人有什么问题?但是,如果没有Thread.Sleep(1),则无论执行多少任务,2个线程执行速度最快,1个线程位于第2位,其他线程以相同的毫秒数挂起,但速度均低于1和2个线程。
新编辑我还尝试在Runnable类的run()方法中添加更多任务(用于计算不是1或10或100个Collatz序列的循环),以便线程本身可以完成更多工作。不幸的是,这也没有帮助。也许我错误地启动了这些任务?任何想法?
编辑所以看起来在向run方法添加更多任务后,它会稍微修复一下,但对于更多线程,问题仍然是8+。我仍然想知道这是因为创建和运行线程比执行任务需要更多的时间吗?或者我应该用这个问题创建一个新帖子?
您不是在等待完成任务,只是测量将它们提交给执行者所花费的时间。
executor.shutdown()
不等待所有任务完成。之后你需要打电话给executor.awaitTermination
。
executor.shutdown();
executor.awaitTermination(5, TimeUnit.HOURS);
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown()
更新我认为我们的测试方法存在缺陷。我在我的机器(1个处理器,2个核心,4个逻辑处理器)上重复测试,从运行到运行测量的时间差别很大。
我认为以下是主要原因:
为了测试这个,我将你的测试转换为JMH。特别是:
我在下面收到的结果与我的预期一致:一个核心在主线程中等待,工作在一个核心上执行,数字是相同的。
Benchmark Mode Cnt Score Error Units
SpeedTest.multipleThreads avgt 20 559.996 ± 20.181 ms/op
SpeedTest.singleThread avgt 20 562.048 ± 16.418 ms/op
更新的代码:
public class ParallelCollatz implements Callable<Long> {
private final long inputNumInit;
public ParallelCollatz(long inputNumInit) {
this.inputNumInit = inputNumInit;
}
@Override
public Long call() {
long result = 1;
long inputNum = inputNumInit;
//main recursive computation
while (inputNum > 1) {
if (inputNum % 2 == 0) {
inputNum = inputNum / 2;
} else {
inputNum = inputNum * 3 + 1;
}
++result;
}
return result;
}
}
和基准本身:
@State(Scope.Benchmark)
public class SpeedTest {
private static final int NUM_TASKS = 1000000;
private static List<ParallelCollatz> tasks = buildTasks();
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@SuppressWarnings("unused")
public long singleThread() throws Exception {
ThreadPoolExecutor executorOneThread = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
return measureTasks(executorOneThread, tasks);
}
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@SuppressWarnings("unused")
public long multipleThreads() throws Exception {
ThreadPoolExecutor executorMultipleThread = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
return measureTasks(executorMultipleThread, tasks);
}
private static long measureTasks(ThreadPoolExecutor executor, List<ParallelCollatz> tasks) throws InterruptedException, ExecutionException {
long sum = runTasksInExecutor(executor, tasks);
return sum;
}
private static long runTasksInExecutor(ThreadPoolExecutor executor, List<ParallelCollatz> tasks) throws InterruptedException, ExecutionException {
List<Future<Long>> futures = new ArrayList<>(NUM_TASKS);
for (int i = 0; i < NUM_TASKS; i++) {
Future<Long> f = executor.submit(tasks.get(i));
futures.add(f);
}
executor.shutdown();
boolean tempFirst = false;
try {
tempFirst = executor.awaitTermination(5, TimeUnit.HOURS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long sum = 0l;
for (Future<Long> f : futures) {
sum += f.get();
}
//System.out.println(sum);
return sum;
}
private static List<ParallelCollatz> buildTasks() {
List<ParallelCollatz> tasks = new ArrayList<>();
for (int i = 1; i <= NUM_TASKS; i++) {
ParallelCollatz task = new ParallelCollatz((long) (i + NUM_TASKS));
tasks.add(task);
}
return tasks;
}
}