我使用的是四核PC(Intel CORE i7),但是我在4个线程上执行任务需要14s,而不是大约6s,这是一个线程执行任务所花费的时间。是因为所有的初始化(其他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
将Exception
添加到调用方法时,不会得到try { (new MyTestCase("test")).runBare(); } catch (Throwable throwable) { throwable.printStackTrace(); }
。如果你得到java.lang.IllegalAccessException: Class junit.framework.TestCase can not access a member of class ...MyTestCase with modifiers "public"
将班级以及包括该班级在内的班级公开
如果得到junit.framework.AssertionFailedError: Method "test" not found
,则将参数更改为new MyTestCase("test")
以反映函数的名称,或者将函数的名称更改为要测试
如果无法通过这种方法解决您的问题,请向我们展示一个MyTestCase类,该类具有该行为。
关于java - 在四核上使用Executors.newFixedThreadPool在2或4个将来提交之间没有区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23008032/