Java:如何根据cpu核心扩展线程? [英] Java: How to scale threads according to cpu cores?

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

问题描述

我不是一个优秀的java程序员,这只是我的爱好,但我渴望知道的不仅仅是普通的东西。

I'm not a good java programmer, it's just my hobby, but I'm eager to know more than average stuff.

我想解决一个数学问题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核心的数量。
和我的问题是,我在互联网上找不到一个简单的教程。我找到的只是固定线程的例子。

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

那么你能帮我找一个好的tuturial的链接还是能给我一个简单而好的例子?这将是非常好的:)

So could you help me with a link to a good tuturial or could give me an easy and good example? That would be really nice :)

推荐答案

您可以使用静态运行时确定Java虚拟机可用的进程数方法, 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 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.

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

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