我使用的是四核 PC(Intel CORE i7),但我在 4 个线程上执行该任务,需要 14 秒,而不是大约 6 秒,这是一个线程执行该任务所需的时间。是因为所有的初始化(创建其他 3 个线程,...)吗?
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import com.google.common.base.Stopwatch;
public class MultithreadWithExecutor {
private static class ExecuteLongTask implements Callable<Integer>{
private static final int ARRAY_SIZE = 10000;
private static final int NB_TEST_ALL = 10000;
private static final int NB_TEST_QUART = NB_TEST_ALL/4;
@Override
public Integer call() throws Exception {
for (int i = 0; i < NB_TEST_QUART; i++) {
//Create a list
List<Double> lst = new ArrayList<Double>();
for (int j = 0; j < ARRAY_SIZE; j++) {
lst.add(Math.random());
}
//sort it
Collections.sort(lst);
}
return 0;
}
}
public static void main(String[] ar) throws InterruptedException, ExecutionException {
int n = 4;
// Build a fixed number of thread pool
ExecutorService pool = Executors.newFixedThreadPool(n);
Stopwatch watch = Stopwatch.createStarted();
Future<Integer> future1 = pool.submit(new ExecuteLongTask());
Future<Integer> future2 = pool.submit(new ExecuteLongTask());
Future<Integer> future3 = pool.submit(new ExecuteLongTask());
Future<Integer> future4 = pool.submit(new ExecuteLongTask());
// Wait until threads finish
int testRuns= future1.get();
testRuns+=future2.get();
testRuns+=future3.get();
testRuns+=future4.get();
long elapsed = watch.elapsed(TimeUnit.MILLISECONDS);
// took ~14s instead of ~6s (time taken by on thread to execute the task)
System.out.println("Runned: "+testRuns+" in: "+elapsed);
pool.shutdown();
}
}
最佳答案
检查以下事项:
- 您的测试未在共享对象上使用
synchronized
- 添加
try { (new MyTestCase("test")).runBare(); 时不会出现
到您的调用方法。如果你得到Exception
} catch (Throwable throwable) { throwable.printStackTrace(); }java.lang.IllegalAccessException:类 junit.framework.TestCase 无法访问类的成员...带有修饰符“public”的 MyTestCase
使该类以及包含该类的类成为公共(public)<- 如果出现
junit.framework.AssertionFailedError: Method "test"not find
,请将参数更改为new MyTestCase("test")
以反射(reflect)您的名称函数或更改要测试的函数的名称
如果您的问题无法通过这种方式解决,请向我们展示一个表现出该行为的 MyTestCase 类。
关于java - 在四核上使用 Executors.newFixedThreadPool 进行 2 次或 4 次 Future 提交没有区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23008032/