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



输出:









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值