在Java中使用并行机制会使程序变慢(慢四倍!!!) [英] Using parallelism in Java makes program slower (four times slower!!!)

查看:94
本文介绍了在Java中使用并行机制会使程序变慢(慢四倍!!!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写共轭梯度方法的实现.

I'm writing conjugate-gradient method realization.

我使用Java多线程进行矩阵反向替换. 使用CyclicBarrier CountDownLatch进行同步.

I use Java multi threading for matrix back-substitution. Synchronization is made using CyclicBarrier, CountDownLatch.

为什么要花这么多时间来同步线程? 还有其他方法吗?

Why it takes so much time to synchronize threads? Are there other ways to do it?

代码段

private void syncThreads() {

    // barrier.await();

    try {

        barrier.await();

    } catch (InterruptedException e) {

    } catch (BrokenBarrierException e) {

    }

}

推荐答案

总共使用了多少个线程?那可能是您问题的根源.只有在以下情况下使用多个线程才能真正提高性能:

How many threads are being used in total? That is likely the source of your problem. Using multiple threads will only really give a performance boost if:

  • 线程中的每个任务都会执行某种阻塞.例如,等待I/O.在这种情况下使用多个线程可以使阻塞时间被其他线程使用.
  • 或您具有多个核心.如果您有4个核心或4个CPU,则可以同时执行4个任务(或4个线程).

听起来您没有在线程中阻塞,所以我猜您正在使用太多线程.例如,如果您使用10个不同的线程同时执行工作,但只有2个内核,则这可能比按顺序运行所有任务要慢得多.通常,启动的线程数等于您的内核/CPU数.每次增加缓慢增加性能的线程数.这将为您提供最佳的线程数.

It sounds like you are not blocking in the threads so my guess is you are using too many threads. If you are for example using 10 different threads to do the work at the same time but only have 2 cores, that would likely be much slower than running all of the tasks in sequence. Generally start the number of threads equal to your number of cores/CPUs. Increase the threads used slowly gaging the performance each time. This will give you the optimal thread count to use.

这篇关于在Java中使用并行机制会使程序变慢(慢四倍!!!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆