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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值