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()釋放進程

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