为什么我的ExecutorService无法执行任务?

时间:2019-04-23 21:02:51

标签: java threadpool executorservice threadpoolexecutor forkjoinpool

我正在与不同的ExecutorServices一起测试他们执行我提交的任务的方式。 下面的代码演示了我测试了哪些服务,以及它们如何接收要执行的任务。

主要我想知道,为什么WorkStealingPool入睡(请参见下面的结果),但是CachedThreadPool可以按预期工作?

void start() {
    ExecutorService service;

    // The different services I tried:
    service = Executors.newFixedThreadPool(1);
    // service = Executors.newCachedThreadPool();
    // service = Executors.newWorkStealingPool();

    Runnable r = () -> {
        Callable<Integer> result = () -> {
            Future<Integer> future = service.submit(() -> 1 + 1);
            return service.submit(() -> (future.get() / 2)).get();
        };
    };

    // Things I tried:

    // 1. Run via separate Thread:
    // Thread t = new Thread(r);
    // t.start();

    // 2. Submit to service:
    service.submit(r);

    // 3. Run directly:
    // r.run();
}

我当前的测试结果是:

service  executiontype  behavior
1  1  1
2  1  2
3  1  3
1  2  1
2  2  2
3  2  3
1  3  1
2  3  4
3  3  5

service
1  FixedThreadPool
2  CachedThreadPool
3  WorkStealingThreadPool

executiontype
1  separate thread
2  submit to service
3  run directly

behavior
1  Short activity on one thread, GUI not responding
2  Everything executes as expected, GUI thread not blocked
3  Threads are being active but some go into wait and remain waiting.
   GUI has to be shutdown by force.
   Multiple calculation invokations deliver the result sometimes.
4  Like #3 but with blocked/waiting GUI thread
5  Like #2 but GUI thread blocked (as expected)

1 个答案:

答案 0 :(得分:0)

我相信您应该执行以下操作:

service.execute(Runnable command)

查看JavaDoc:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

如果您希望单独旋转每个线程,那将是您的最佳选择。