MyException - 我的异常网
当前位置:我的异常网» 互联网 » 容易的压测模拟

容易的压测模拟

www.MyException.Cn  网友分享于:2018-05-16  浏览:0次
简单的压测模拟
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class CountExample {
	
	private static final int clientTotal = 5000;
	
	private static final int threadTotal = 8;
	
	private static AtomicInteger count = new AtomicInteger(0);
	
	public static void main(String... args) {
		
		ExecutorService executorService = Executors.newFixedThreadPool(threadTotal);
		final CountDownLatch latch = new CountDownLatch(clientTotal);
		final Semaphore semaphore = new Semaphore(threadTotal);
		LocalDateTime start = LocalDateTime.now();
		for (int i = 0; i < clientTotal; i++) {
			
			executorService.execute(() -> {
				
				try {
					
					semaphore.acquire();
					add();
					System.out.println(String.format("add() invoked by %s => %d", Thread.currentThread().getName(), count.get()));
					semaphore.release();
					latch.countDown();
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			});
		}
		try {
			
			latch.await();
			LocalDateTime end = LocalDateTime.now();
			System.out.println(String.format("cost time millis : %d", Duration.between(start, end).toMillis()));
			executorService.shutdown();
			System.out.println(String.format("count:%d", count.intValue()));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void add() {
		
		count.getAndIncrement();
	}
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有