FutureTasks 和 CachedThreadPool 如何工作

发布于 2024-08-24 04:50:26 字数 764 浏览 6 评论 0原文

我目前有执行以下操作的代码:

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);
}

我遇到的问题是我让每个未来任务打印出它们在进行计算时花费的时间,因此例如在控制台上我会看到

first_task : 20000ms
second_task : 18000ms
...

总时间 (< code>System.out.println(time take)) 比任何未来任务所花费的最长时间要大得多,因此根据此示例,方法 do 将花费大约 1 分钟(与 first_task 的 20 秒相比) )。

我的印象是这些未来的任务是并行运行的,但从时间安排来看,它们似乎是一个接一个地运行的。我是否正确使用了这个 API?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

又怨 2024-08-31 04:50:26

您正确使用了 API,但请记住,每个任务都在单独的线程中运行,而不是单独的进程(因此不一定是并行的)。

每个线程必须在单独的 CPU 核心上运行才能同时执行。这是否可行取决于您的机器、其当前负载以及 JVM 和操作系统如何跨内核调度线程。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文