java并发测试例子

java并发测试例子

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static final CountDownLatch startLatch = new CountDownLatch(1);
;
public static CountDownLatch endLatch;
public static int loopCount;
int clientNum;
public Test(String[] args) {
if (args == null || args.length < 2) {
throw new RuntimeException("must input 2 paramter:clientNum,loopCount");
}
clientNum = Integer.parseInt(args[0]);
loopCount = Integer.parseInt(args[1]);
endLatch = new CountDownLatch(clientNum);
}
public void start() {
ExecutorService executor = Executors.newFixedThreadPool(clientNum);
for (int j = 0; j < clientNum; j++) {
executor.submit(new Runnable() {
public void run() {
exec(startLatch, endLatch);
}
});
}
try {
startLatch.countDown();
long start = System.currentTimeMillis();
endLatch.await();
long used = System.currentTimeMillis() - start;
System.out.println("client num:" + clientNum + ",execute loopCount client:" + loopCount + ",total execute:" + loopCount * clientNum + ",total time:" + used / 1000 + "s, tps:" + loopCount * clientNum * 1000.0 / used);
executor.shutdown();
System.exit(0);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void exec(CountDownLatch startLatch, CountDownLatch endLatch) {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
new Client().start();
}
public static void main(String[] args) throws InterruptedException {
/*加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Thread.sleep(6000);*/
args = new String[2];
args[0] = "200"; //客户端并发数
args[1] = "300000"; //调用次数
new Test(args).start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package concurrent;
public class Client {
public void start() {
try {
long start = System.currentTimeMillis();
int count = Test.loopCount;
Services services = new Services();
for (int i = 0; i < count; i++) {
String result = services.hello("donie");
}
Test.endLatch.countDown();
long used = System.currentTimeMillis() - start;
System.out.println("tps " + count * 1000.0 / used);
} catch (Exception e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
package concurrent;
public class Services {
public String hello(String str){
return str;
}
}
文章目录
  1. 1. java并发测试例子
,