如何根据CPU内核扩展线程? [英] How to scale threads according to CPU cores?

查看:93
本文介绍了如何根据CPU内核扩展线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java解决带有多个线程的数学问题.我的数学问题可以分为多个工作单元,我想通过几个线程来解决.

I want to solve a mathematical problem with multiple threads in Java. my math problem can be separated into work units, that I want to have solved in several threads.

我不希望有固定数量的线程在工作,而是与CPU核心数量匹配的线程数量.我的问题是,为此我在互联网上找不到简单的教程.我发现的只是带有固定线程的示例.

I don't want to have a fixed amount of threads working on it, but instead an amount of threads matching the amount of CPU cores. My problem is, that I couldn't find an easy tutorial in the internet for this. All I found are examples with fixed threads.

这怎么办?你能提供例子吗?

How can this be done? Can you provide examples?

推荐答案

您可以通过使用静态运行时方法

You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, availableProcessors. Once you have determined the number of processors available, create that number of threads and split up your work accordingly.

更新:为进一步说明,线程只是Java中的一个对象,因此您可以像创建任何其他对象一样创建它.因此,假设您调用了上面的方法并发现它返回了2个处理器.惊人的.现在,您可以创建一个循环,该循环生成一个新线程,并拆分该线程的工作,然后触发该线程.这是一些伪代码来说明我的意思:

Update: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object. So, let's say that you call the above method and find that it returns 2 processors. Awesome. Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread. Here's some psuedocode to demonstrate what I mean:

int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
  Thread yourThread = new AThreadYouCreated();
  // You may need to pass in parameters depending on what work you are doing and how you setup your thread.
  yourThread.start();
}

有关创建自己的线程的更多信息,请前往本教程的标题.另外,您可能需要查看线程池来创建线程.

For more information on creating your own thread, head to this tutorial. Also, you may want to look at Thread Pooling for the creation of the threads.

这篇关于如何根据CPU内核扩展线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆