即时通讯在Java中进行了一些并发实验。我有这种主要的计算方法,仅用于模拟半昂贵的操作:
static boolean isprime(int n){
if (n == 1)
return false;
boolean flag = false;
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag = true;
break;
}
}
return ! flag;
}
然后,我有了这个主要方法,该方法只计算从0到N的所有素数,并将结果存储在布尔数组中:
public class Main {
public static void main(String[] args) {
final int N = 100_000;
int T = 1;
boolean[] bool = new boolean[N];
ExecutorService es = Executors.newFixedThreadPool(T);
final int partition = N / T;
long start = System.nanoTime();
for (int j = 0; j < N; j++ ){
boolean res = isprime(j);
bool[j] = res;
}
System.out.println(System.nanoTime()-start);
}
这给了我这样的结果:893888901 n / s 848995600 n / s
我也有此驱动程序代码,在这里我使用了executorservice,在其中我使用了一个线程来执行相同的操作:
public class Main {
public static void main(String[] args) {
final int N = 100_000;
int T = 1;
boolean[] bool = new boolean[N];
ExecutorService es = Executors.newFixedThreadPool(T);
final int partition = N / T;
long start = System.nanoTime();
for (int i = 0; i < T; i++ ){
final int current = i;
es.execute(new Runnable() {
@Override
public void run() {
for (int j = current*partition; j < current*partition+partition; j++ ){
boolean res = isprime(j);
bool[j] = res;
}
}
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.MILLISECONDS);
} catch (Exception e){
System.out.println("what?");
}
System.out.println(System.nanoTime()-start);
}
这样得出的结果是:9523201 n / s,15485300 n / s。
现在,你可以阅读第二个示例,它比第一个示例快得多。我真的不明白为什么会这样吗?exercutorservice线程(具有1个线程)是否应该慢一些,因为与主线程相比,它基本上是按顺序执行工作,而又是“唤醒”线程的开销?
当我开始添加多个线程时,我期望executorservice更快,但这有点违反直觉。
这是代码底部的超时。如果将其设置得更高,则执行时间将非常相似。
es.awaitTermination(1000, TimeUnit.MILLISECONDS);
你提到的第一个主程序的执行时间比允许第二个主程序等待线程完成的毫秒数要高得多。
感谢您可以尝试一下,但这不是基准测试中有些人为的成分吗?如果我只是将延迟设置得更高一些,那么executorservice会变慢吗?
您只需要停止等待即可-在测量时间之前,可能尚未完成执行。