java代码模拟高并发,多线程之CountDownLatch,Semaphore

标题通过c可以模拟高并发,多线程

需要测试的高并发或多线程的业务代码
package test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 主业务类
 *
 */
public class Common {

	private int count = 0;
	private AtomicInteger atomicInteger = new AtomicInteger(0);
	public void add() {
		count++;
	}
	public void addAtomicInteger() {
		atomicInteger.addAndGet(1);
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public AtomicInteger getAtomicInteger() {
		return atomicInteger;
	}
	public void setAtomicInteger(AtomicInteger atomicInteger) {
		this.atomicInteger = atomicInteger;
	}	
	
	
}
通过过CountDownLatch,Semaphore来测试该业务代码
package test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 测试多线程高并发
 * 
 * @author hWX393213
 *
 */
public class ConcurrencyTest {

	// 请求总数
	public static int clientTotal = 5000;

	// 同时并发的线程数
	public static int threadTotal = 200;

	public static void main(String[] args) {
		// 创建线程池
		ExecutorService executorService = Executors.newCachedThreadPool();
		// 定义信号量
		final Semaphore semaphore = new Semaphore(threadTotal);
		//定义计数器闭锁
		final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

		//需要测试的业务主类
		Common common = new Common();
		for (int i = 0; i < clientTotal; i++) {
			//将需要测试的业务全部放入线程池
			executorService.execute(() -> {
				try {
					//当线程允许被执行时才执行
					semaphore.acquire();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//需要测试的主业务的具体方法
				common.add();//测试int是否线程安全
				common.addAtomicInteger();//测试AtomicInteger是否线程安全
				
				//线程执行完后释放
				semaphore.release();
				//每次线程执行完之后,countdown一次
				countDownLatch.countDown();
			});

		}
		try {
			//该方法可以保证clientTotal减为0.既可以保证所有的线程都执行完毕了
			countDownLatch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//所有的线程执行完了后,关闭线程池
		executorService.shutdown();
		System.out.println("count=" + common.getCount() + "~AtomicInteger=" + common.getAtomicInteger());
	}
}

CountDownLatch说明

CountDownLatch是一种java.util.concurrent包下一个同步工具类,从字面的意思理解,用在多线程中就是一个倒计时器,当倒计时数到0时,就是表示多线程所有的完成,核心代码countDownLatch.countDown()和countDownLatch.await();
countDownLatch.await()该方法可以保证clientTotal减为0.既可以保证所有的线程都执行完毕了

Semaphore说明

Semaphore 信号量,核心代码semaphore.acquire()和semaphore.release();
semaphore.acquire()判断进程是否满足执行条件,若满足才继续下一步
semaphore.release()释放进程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章