1. 程式人生 > >Java 多執行緒 CountDownLatch 試用

Java 多執行緒 CountDownLatch 試用

簡述:

使用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());
	}
}



輸出: