并发测试->countDownLatch

public class TheadTest {

static final int threadSize = 2000; //最大并发数量
static CountDownLatch countDownLatch1 = new CountDownLatch(1);
static CountDownLatch countDownLatch2 = new CountDownLatch(threadSize);

public static void threadTest() throws InterruptedException{
//开始时间
long beginTime = System.currentTimeMillis();
for (int i = 0; i < threadSize; i++) {
//创建子线程并使其阻塞
new Thread(new Runnable() {
public void run() {
try {
//阻塞到countDownLatch1为0时在开始执行
countDownLatch1.await();
//System.out.println("需要执行的操作");
//将countDownLatch2减一
countDownLatch2.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
//使所有的子线程开始并发执行
countDownLatch1.countDown();
//阻塞主线程
countDownLatch2.await();
//结束时间
long endTime = System.currentTimeMillis();
//执行花费时间
System.out.println("thread size : "+threadSize+", use pool :"+(endTime-beginTime));
}
}

猜你喜欢

转载自www.cnblogs.com/zdaoma/p/12066959.html