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.




你可能感兴趣的:(java,jvm,多线程,linux,OS)