环境:Linux Redhat 5.4 32位,CPU8核
Java代码如下:
class Loop {
public static void main(String[] args) {
for(int i=0;i<7;i++)
new Thread(new Runnable(){
public void run() {
while(true);
}
}).start();
while(true);
}
}
编译后启动,输入top命令可看到:
Tasks: 215 total, 1 running, 214 sleeping, 0 stopped, 0 zombie
Cpu(s):100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 16580348k total, 7986304k used, 8594044k free, 577356k buffers
Swap: 16777208k total, 0k used, 16777208k free, 5988556k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18833 flow 18 0 1176m 18m 7620 S 798.5 0.1 2:11.62 java
按1后可显示每个CPU核的情况:
top - 15:02:39 up 15 days, 3:40, 4 users, load average: 7.17, 2.92, 1.24
Tasks: 215 total, 1 running, 214 sleeping, 0 stopped, 0 zombie
Cpu0 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu1 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu2 : 99.7%us, 0.3%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu3 : 99.3%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.3%hi, 0.3%si, 0.0%st
Cpu4 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu5 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu6 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu7 :100.0%us, 0.0%sy, 0.0%ni, 0.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 16580348k total, 7986616k used, 8593732k free, 577396k buffers
Swap: 16777208k total, 0k used, 16777208k free, 5989628k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18833 flow 18 0 1176m 18m 7620 S 793.3 0.1 9:44.87 java
由此可见8个线程占用了8个CPU核的资源,资源达到100%。
我们修改下代码,改成:
class Loop {
public static void main(String[] args) {
while(true);
}
同样按top命令,可看到就只有1个CPU达到100%(注某一时刻可能是核1,过会可能是核2),其他几个CPU核均很小。
由此可见,1个线程只会使用1个cpu核资源,多线程可充分利用物理资源。
看过Mina的童鞋应该知道,Mina的推荐的IoProcessor线程池IO线程数为核数+1就是这个原因。