简体   繁体   English

如何使Java与线程一起使用多个核心?

[英]how to make Java uses multiple cores with threads?

This is a similar question to the one appearing at: How to ensure Java threads run on different cores . 这与出现的问题类似: 如何确保Java线程在不同的核心上运行 However, there might have been a lot of progress in that in Java, and also, I couldn't find the answer I am looking for in that question. 但是,在Java中可能会有很多进展,而且,我找不到我在该问题中寻找的答案。

I just finished writing a multithreaded program. 我刚刚写完一个多线程程序。 The program spawns several threads, but it doesn't seem to be using more than a single core. 该程序产生了几个线程,但它似乎没有使用多个线程。 The program is faster (I am parallelizing something which makes it faster), but it definitely does not use all cores available, judging by running "top". 该方案更快(我并行的东西,这使得它更快),但它绝对不会使用所有可用的核心,通过运行“顶”判断。

Any ideas? 有任何想法吗? Is that an expected behavior? 这是预期的行为吗?

The general code structure is as following: 一般代码结构如下:

   for (some values in i)
   {
        start a thread of instantiated as MyThread(i)
        (this thread uses heavily ConcurrentHashMap and arrays and basic arithmetic, no IO)
        add the thread to a list T
   }

   foreach (thread in T)
   {
        do thread.join()
   }

If its almost exactly 100% of one CPU, it can mean you really have 如果它几乎完全是一个CPU的100%,它可能意味着你真的拥有

  • one core thread which is doing all the work and the others are not doing so much. 一个核心线程正在完成所有工作而其他人没有这么做。
  • one resource which you are locking on and only one thread has a chance to run. 您锁定的一个资源,只有一个线程有机会运行。

If you are using approximately one CPU it can mean this is all the work your CPUs have because you are waiting for something such as IO (network and/or disk) 如果您使用大约一个CPU,那么这可能意味着这是您的CPU所具有的所有工作,因为您正在等待IO(网络和/或磁盘)等内容

I suggest you look at the state of your threads in VisualVM. 我建议你看一下VisualVM中你的线程的状态。 It will help you identify which threads are running and give you an ideal of their pattern of behaviour. 它将帮助您确定正在运行的线程,并为您提供理想的行为模式。 I also suggest you use a CPU profiler to help find your bottlenecks. 我还建议你使用CPU分析器来帮助找到你的瓶颈。

I think I read in the SCJP book by Katherine Sierra that JVM's ask the underlying OS to create a new OS thread for every Java thread. 我想我在Katherine SierraSCJP书中读到,JVM要求底层操作系统为每个Java线程创建一个新的OS线程。

So it's up to the underlying Operating System to decide how to balance Java (and any other kind of) threads between the available CPU's. 因此,由底层操作系统来决定如何在可用CPU之间平衡Java(和任何其他类型)线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM