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

查看:36
本文介绍了如何根据 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?

推荐答案

您可以通过使用静态运行时方法 availableProcessors.确定可用处理器的数量后,创建该数量的线程并相应地拆分您的工作.

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 pseudocode 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天全站免登陆