一个简单的并发测试的例子: 当线程数达到规定的数量,并发执行
package com.http.concurrent.test;
import java.util.concurrent.CyclicBarrier;
/**
* 测试业务处理线程
* @author lijunqing
*/
public abstract class WorkRun implements Runnable {
private final CyclicBarrier barrier;
public WorkRun(CyclicBarrier barrier) {
this.barrier=barrier;
}
public void run() {
try {
System.out.println(Thread.currentThread().getId() + " thread is awaiting");
barrier.await();
process();
} catch(Exception e) {
e.printStackTrace();
}
}
protected abstract void process();
}
每个测试的都继承WorkRun;实现process借口,
测试例子:
public static void main(String[] args) {
int count=1000;
CyclicBarrier barrier=new CyclicBarrier(count);
ExecutorService executorService=Executors.newFixedThreadPool(count);
for(int i=0; i < count; i++) {
executorService.execute(new LoginTest(barrier));
}
executorService.shutdown();
long starttime=System.currentTimeMillis();
while(!executorService.isTerminated()) {
System.out.println("有没有关闭的");
}
long endtime=System.currentTimeMillis();
System.out.println("starttime:" + starttime + " endtime:" + endtime+" 所有线程完成用时:"+(endtime-starttime));
}
结果:
8 thread is awaiting
10 thread is awaiting
9 thread is awaiting
12 thread is awaiting
11 thread is awaiting
********
37 thread is awaiting
39 thread is awaiting
1006 thread is awaiting
1007 thread is awaiting
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
*********
有没有关闭的
有没有关闭的
1005 thread is awaiting
1003 thread is awaiting
1004 thread is awaiting
999 thread is awaiting
1001 thread is awaiting
*****
62 thread is awaiting
60 thread is awaiting
55 thread is awaiting
57 thread is awaiting
53 thread is awaiting
58 thread is awaiting
56 thread is awaiting
54 thread is awaiting
52 thread is awaiting
51 thread is awaiting
49 thread is awaiting
47 thread is awaiting
50 thread is awaiting
48 thread is awaiting
46 thread is awaiting
45 thread is awaiting
43 thread is awaiting
41 thread is awaiting
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
*****
有没有关闭的
--start--working--43
*******
--start--working--168
--start--working--164
--start--working--166
--start--working--163
--start--working--165
--start--working--170
--start--working--172
--start--working--167
--start--working--178
--start--working--174
--start--working--180
--start--working--176
--start--working--169
--start--working--171
*******
--start--working--41
有没有关闭的
starttime:1394614101246 endtime:1394614101855 所有线程完成用时:609