1. 程式人生 > >Java 使用 CountDownLatch 模擬1000一個併發訪問

Java 使用 CountDownLatch 模擬1000一個併發訪問

package com.zzf.concurrence.cdtest;



import java.util.concurrent.CountDownLatch;



public class CountdownLatchTest {



private static CountDownLatch cd = new CountDownLatch(1000);



private static final int CONCURRENCE_COUNT = 1000 + 1;



public static void main(String[] args) {

// 一千個執行緒,同時懟一個方法



for (int i = 0; i < CONCURRENCE_COUNT; i++) {

new Thread(new SendTask()).start();

cd.countDown();



}



long currentTimeMillis = System.currentTimeMillis();

try {

cd.countDown();

cd.await();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}



System.out.println("當前用時:" + (System.currentTimeMillis() - currentTimeMillis));



}



private static class SendTask implements Runnable {



@Override

public void run() {

try {

cd.await();

} catch (InterruptedException e) {

e.printStackTrace();

}



sendsms();

}



}



private static void sendsms() {



// System.out.println("資訊傳送成功"+System.currentTimeMillis());



}



}