欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的压测模拟

程序员文章站 2022-07-10 15:02:46
...
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();
	}
}

相关标签: java 压测