【发布时间】:2019-10-14 23:35:28
【问题描述】:
我在 Java 中测试并发性,我的目标是确定拥有多个线程是否真的有益,但是,我得到的结果并不相加。我正在尝试优化阶乘函数,对于这个特定的测试,我使用的是 1e9!我想要结果模 1e9+7 这样它就不会溢出。首先,我根据 number_of_threads 划分数量,并分别为每个线程分配它们的工作。然后我照常做,比较我得到的时间。似乎当 number_of_threads = 4 时,我得到的结果比没有线程的版本更好,这是有道理的,因为我的 CPU 有 4 个内核。正如预期的那样,与只有 4 个相比,任何数量大于 4 的线程都具有更慢的时间。但是,当使用少于 4 个线程执行此操作时,结果会变得很大,例如,使用 1 个线程我希望它的持续时间与执行相同它没有线程+开销。没有线程我得到 6.2 秒和 19.3 有 1 个线程,这对于它来说差别太大了。
为了测试原因,我在 run 方法上放置了一些计数器,有时似乎只执行其中的 for 的 1 个周期需要超过一毫秒,而且不应该,因为它只是两个操作加上计时器。
public class Calc implements Runnable{
long min, max, mod, res;
Res r;
public Calc(long min, long max, long mod, Res r) {
this.min = min;
this.max = max;
this.mod = mod;
res = 1;
this.r = r;
}
public void run() {
for(long i = min; i <= max; i++) {
res *= i;
res %= mod;
}
r.addup(res);
}
}
public class Res{
long result;
long mod;
public Res(long mod) {
result = 1;
this.mod = mod;
}
public synchronized void addup(long add) {
result *= add;
result %= mod;
}
public long getResult() {
return result;
}
}
public class Main{
public static void main(String args[]) {
long startTime = System.nanoTime();
final long factorial = 1000000000L;
final long modulo = 1000000007L;
Res res = new Res(modulo);
int number_of_threads = 1;
Thread[] c = new Thread[number_of_threads];
long min = 1, max = factorial/(long)number_of_threads;
long cant = max;
for(int i = 0; i < number_of_threads; i++) {
if((long)i < (factorial % number_of_threads))max++;
c[i] = new Thread(new Calc(min, max, modulo, res));
c[i].start();
min = max +1;
max += cant;
}
for(int i = 0; i < number_of_threads; i++) {
try {
c[i].join();
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(res.getResult());
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println((double)totalTime/1000000000L);
}
}
当 number_of_threads = 1 时,我得到 19.3 秒。当 number_of_threads = 2 我得到 10.1 秒。当 number_of_threads = 3 我得到 7.1 秒。当 number_of_threads = 4 时,我得到 5.4 秒。在没有线程的情况下,我得到 6.2 秒(我用相同的方法计算这个时间)
只有 1 线程和没有线程之间应该没有太大区别,并且对于 2 和 3 线程应该比没有线程快。为什么会这样,有什么办法可以解决吗?谢谢。
编辑:添加无线程版本
public class Main{
public static void main(String args[]) {
long startTime = System.nanoTime();
final long factorial = 1000000000L;
final long modulo = 1000000007L;
long res = 1;
for(long i = 1; i <= factorial; i++) {
res *= i;
res %= modulo;
}
System.out.println(res);
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println((double)totalTime/1000000000L);
}
}
【问题讨论】:
-
创建线程是一个昂贵的过程,因此需要一些时间才能获得回报。尝试使用 ThreadPoolExecutor,然后在创建之后进行计时 (docs.oracle.com/javase/7/docs/api/java/util/concurrent/…)
-
@racraman 是的,我知道创建线程的开销,我会按照建议尝试使用 ThreadPoolExecutor,但是,上面的代码仍然没有意义。
-
@gimape07 这就是 cmets 的用途。
-
你能发布你的“无线程”版本来比较吗?
-
@ErwinBolwidt 当然!
标签: java multithreading time cpu