感興趣的同學可以把下面的代碼copy到機器上執行看看(例如java GenRandomStringTest 50 100 1024),會發現是挺耗CPU的,原因是什麼呢? 有什麼建議嗎?
GenRandomStringTest代碼如下,也可從這下載:
import java.util.Random;
public class GenRandomStringTest {
public static void main(String[] args) throws Exception{
int threadNums = Integer.parseInt(args[0]);
int keySize = Integer.parseInt(args[1]);
int valueSize = Integer.parseInt(args[2]);
for (int i = 0; i < threadNums; i++) {
new Thread(new Test(keySize,valueSize)).start();
}
}
}
class Test implements Runnable{
private Random rand = new Random();
private int keySize = 0;
private int valueSize = 0;
public Test(int keySize,int valueSize){
this.keySize = keySize;
this.valueSize = valueSize;
}
public void run() {
while(true){
RandomStringUtils.generateBytes(keySize);
RandomStringUtils.generateBytes(valueSize);
try{
Thread.sleep(rand.nextInt(2));
}
catch(Exception e){
// IGNORE;
}
}
}
}
RandomStringUtils代碼如下,由於blog渲染有問題,會丟失代碼,只好截圖如下了,也可從這下載:
ps: 不過話說以這種方式隨機生成指定大小的字符串還是挺耗時的,也歡迎提供建議,:)