java - 在四核上使用 Executors.newFixedThreadPool 进行 2 次或 4 次 Future 提交没有区别

标签 java java.util.concurrent

我使用的是四核 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/

相关文章:

java - 替换 XML 节点内出现的 >、< 和 & 字符

java - 为什么 Scala ConcurrentMap.putIfAbsent 总是尝试 put?

java - 如果我只需要保证 `happens-before` 关系,而不是原子性,我应该使用并发类还是同步块(synchronized block)?

java - Java 中有多少种内存屏障?

java - 如何从监听器委托(delegate)可运行的代码?

java - 是否可以为同一个 jpa 实体创建多个表?

java - 在 Java 7 中获取正确的 mac 地址

java - 是什么导致了我的 NullPointerException?

java - InetAddress getLocalHost() 未从 C :\WINDOWS\system32\drivers\etc\hosts 返回预期的 IP 地址

java - 执行器服务 : how to prevent thread starvation when synchronization barriers are done in the threads