如何高效地同时运行 10-15 个线程

发布于 2024-11-09 11:25:11 字数 299 浏览 0 评论 0原文

我试图同时运行多个线程,其中每个线程都计算特定时间点的值并返回结果。我正在考虑使用 Executor 类,但似乎做得不正确。我想知道这段代码是否正确。或者说最好的方法是什么?

ExecutorService tasker = Executors.newFixedThreadPool(20);
    for(double t = 0.0; t<=5.0; t = t + 0.50 ){ // t is time interval
        tasker.execute(new MyThread(t));
    }

I am trying to run multiple threads concurrently, where each thread is computing value for a particular point in time and returning a result. I was thinking of using the Executor class but it seems am not doing it correctly. I was wondering if this piece of code is correct for that. Or what is the best way of doing this?

ExecutorService tasker = Executors.newFixedThreadPool(20);
    for(double t = 0.0; t<=5.0; t = t + 0.50 ){ // t is time interval
        tasker.execute(new MyThread(t));
    }

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

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

发布评论

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

评论(2

灯下孤影 2024-11-16 11:25:11

您不需要在执行方法中传递线程。
相反,您需要传递一个 Runnable 对象,如下所示:

ExecutorService tasker = Executors.newFixedThreadPool(20);
for(double t = 0.0; t<=5.0; t = t + 0.50 ){ // t is time interval
    tasker.execute(new MyRunnable(t));
}
....
....
class MyRunnable implements Runnable
{
    MyRunnable(double i)
    {
       System.out.println(i);
       ...
    }
}

You dont need to pass a Thread inside the execute method.
Instead you need to pass a Runnable object, like so:

ExecutorService tasker = Executors.newFixedThreadPool(20);
for(double t = 0.0; t<=5.0; t = t + 0.50 ){ // t is time interval
    tasker.execute(new MyRunnable(t));
}
....
....
class MyRunnable implements Runnable
{
    MyRunnable(double i)
    {
       System.out.println(i);
       ...
    }
}
我不吻晚风 2024-11-16 11:25:11

要真正同时运行 10-15 个线程,您需要有 10-15 个空闲核心。但是,如果您有这么多空闲核心,则需要确保池中至少有这么多线程和至少这么多任务。

对于 CPU 密集型进程,最佳线程数通常是您拥有的核心数。 (有时使用超线程实现双精度)

需要注意的是使用 float 或 double 的循环,这些类型可能存在舍入误差,该误差会随着每次迭代而累积。您最好使用整数并计算您的值。

for(int i=0;i<=10;i++) {
   double t= i/2.0;
   tasker.execute(new MyRunnable(t));
}

To truly run 10-15 threads concurrently you need to have 10-15 free cores. However, if you have this many free cores, you need to ensure you have a pool with at least this many threads and at least this many tasks.

For CPU bound processes, the optimal number of threads is often the number of cores you have. (Sometimes double with hyper-threading)

Something to watch out for is loops which use float or double These types can have rounding error which accumulates with every iteration. You are far better off using an integer and calculate your value.

for(int i=0;i<=10;i++) {
   double t= i/2.0;
   tasker.execute(new MyRunnable(t));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文