簡述: java
使用Java多線程的庫,包括 多線程
ExecutorService線程池, 併發
CountDownLatch線程運行控制(知道全部啓動的線程調用完成後,函數纔會繼續執行) dom
- 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());
- }
- }
輸出: ide