简单的压测模拟


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

你可能感兴趣的:(技术技巧)