Java 多核和多線程

最近在論壇裏看到有人討論多核,那麼,

多核和多線程有啥關聯呢?

我做了個實驗,
實現環境:
AMD Athlon(tm) 64 X2 Dual Core
Ubuntu i386/內核: linux 2.6.32-25
OpenJDK6

1.Main函數裏啓動一個線程時候, 一個CPU 100%

2.Main函數裏啓動兩個線程的時候,2個CPU 100%

3.Main 函數裏1個線程,但同時啓動2次,和效果2類似


結論:系統會自動調配CPU,而且發現系統會自動使用 2個CPU中利用率較小的CPU。
  即,多核CPU運行多線程程序,如果編程時候沒有指定CPU信息,OS會負責CPU內核的調度和管理,不需要考慮OS的多核CPU調度的。但是如果自己想 均衡多核CPU的負載,在創建線程的時候,可以指定線程的CPU親和性(CPU Affinity),使用如 linux c api:sched_setaffinity,windows c api:SetProcessAffinityMask、SetThreadAffinityMask函數,可以實現干預OS對線程的調度,均衡CPU負載。

附:

在指定cpu的核心上執行線程(c/c++): http://www.cppblog.com/Khan/archive/2009/12/29/104384.html

那麼JAVA呢?

In the JRockit JVM Management API you can at least suggest the process affinity. Not sure if it is respected on the OS you're running. See http://e-docs.bea.com/jrockit/releases/R27/javadoc/manapi/docs/com/bea/jvm/JVM.html#suggestProcessAffinity(java.util.Collection) for more information. 

JVM jvm = JVMFactory.getJVM();
List cpus = new ArrayList();
for(Iterator it = JVMFactory.getJVM().getProcessAffinity().iterator();it.hasNext();)
{
 CPU cpu = (CPU) it.next();
 jvm.suggestProcessAffinity(cpus);
}

You can find JRockit here. 
http://www.oracle.com/technology/software/products/jrockit/index.html



===================================
I used taskset on my 4 cpu machine, and by using:
taskset -pc 0 java net.tilialacus.BusyThreads
I gbound all threads to cpu 0. (BusyThreads just runs a few threads with
while(true);

However, if I started the process first, then I have to bind all threads
manually to the CPU. Using ps -eLf I could list all threads (10 or so)
and I could bind each of them separately. I didn't find a way for
taskset to climb the process/thread tree automatically.




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章