如何高效地同时运行 10-15 个线程
我试图同时运行多个线程,其中每个线程都计算特定时间点的值并返回结果。我正在考虑使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要在执行方法中传递线程。
相反,您需要传递一个 Runnable 对象,如下所示:
You dont need to pass a Thread inside the execute method.
Instead you need to pass a Runnable object, like so:
要真正同时运行 10-15 个线程,您需要有 10-15 个空闲核心。但是,如果您有这么多空闲核心,则需要确保池中至少有这么多线程和至少这么多任务。
对于 CPU 密集型进程,最佳线程数通常是您拥有的核心数。 (有时使用超线程实现双精度)
需要注意的是使用 float 或 double 的循环,这些类型可能存在舍入误差,该误差会随着每次迭代而累积。您最好使用整数并计算您的值。
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
ordouble
These types can have rounding error which accumulates with every iteration. You are far better off using an integer and calculate your value.