문제

I currently have code that does the following:

private final static ExecutorService pool = Executors.newCachedThreadPool();
public void foo(){
    FutureTask<MyObject> first_task = createFutureTask();
    FutureTask<MyObject> second_task = createFutureTask();
    ...

    pool.execute(first_task);
    pool.execute(second_task);
    ....
    first_task.get();
    second_task.get();
    ...
    System.out.println(time taken);
}

The problem I'm having is that I get each of the future task to print out the time they take when doing computation, so for example on the console I will see

first_task : 20000ms
second_task : 18000ms
...

but the total time (System.out.println(time taken)) is much larger then the longest time taken by any future task, so in line with this example the method do would take around 1 minute (compared to the 20s of first_task).

I was under the impression that these future tasks run in parallel but from the timings it seems as though they are being run one after the other. Am I using this API correctly?

도움이 되었습니까?

해결책

You're using the API correctly, but keep in mind that each task runs in a separate thread, not a separate process (and thus not necessarily in parallel).

Each thread would have to run on a separate CPU core to actually execute at the same time. Whether or not this is possible depends on your machine, its current load, and how the JVM and OS are able to schedule the threads across cores.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top