感兴趣的同学可以把下面的代码copy到机器上执行看看(例如java GenRandomStringTest 50 100 1024),会发现是挺耗CPU的,原因是什么呢? 有什么建议吗?
GenRandomStringTest代码如下,也可从这下载 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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: 不过话说以这种方式随机生成指定大小的字符串还是挺耗时的,也欢迎提供建议,:).
源码如下:
import java.util.Random; public class RandomStringUtils { private static final String KEY_SEED="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final int KEY_SEED_LEN=KEY_SEED.length(); private static final char[] KEY_SEED_CHARS=KEY_SEED.toCharArray(); private static Random random = new Random(); public static byte[] generateBytes(int length){ StringBuilder keyBuilder=new StringBuilder(length); for (int i = 0; i < length; i++) { keyBuilder.append(KEY_SEED_CHARS[random.nextInt(KEY_SEED_LEN)]); } return keyBuilder.toString().getBytes(); } }