简述:
使用Java多线程的库,包括
ExecutorService线程池,
CountDownLatch线程运行控制(知道所有启动的线程调用完成后,函数才会继续执行)
package test.anialy.multithread;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
public class MultiThreadCountTest {
// 线程处理函数
public static void doSomething() {
try {
Thread.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void main() throws Exception {
final int currency = 10; // 线程池大小
ExecutorService service = Executors.newFixedThreadPool(currency);
final AtomicInteger successThreadCnt = new AtomicInteger(0);
final AtomicLong totalCost = new AtomicLong(0);
int count = 100; // 执行次数
// 所有线程结束
final CountDownLatch block = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
service.execute(new Runnable() {
@Override
public void run() {
try {
long start = System.currentTimeMillis();
// 执行某个函数操作
doSomething();
totalCost.addAndGet(System.currentTimeMillis() - start);
successThreadCnt.incrementAndGet();
} catch (Exception e){
e.printStackTrace();
} finally {
block.countDown();
}
}
});
}
block.await();
System.out.printf("共%s次触发函数doSomething,并发%s,成功%s个,平均耗时: %d ms",
count,
currency,
successThreadCnt.get(),
totalCost.get() / successThreadCnt.get());
}
}
输出: