java并发编程笔记(二)——并发工具

java并发编程笔记(二)——并发工具

工具:

  • Postman:http请求模拟工具
  • Apache Bench(AB):Apache附带的工具,测试网站性能
  • JMeter:Apache组织开发的压力测试工具
  • 代码:Semaphone、CountDownLatch等

PostMan:

Apache Bench(AB)

ab -n [请求总数] -c [本次请求的并发数是50] [url]
例如:ab -1000 -c 50 http://www.baidu.com

JMeter

一个图形化的工具,功能很强大

代码测试模拟并发

CountDownLatch

T1、T2、T3每次执行都会将计数器减1,线程A在计数器减为0的时候,才会执行。

能够保证某一个线程在其他线程执行完之后再执行的需求

Semaphore(信号量)

同一时刻并行的线程数量

主要用来控制同时并发数

并发场景模拟

public class ConcurrencyTest {

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

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

    public static int count = 0;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count);
    }

    private static void add() {
        count++;
    }
}

猜你喜欢

转载自www.cnblogs.com/xujie09/p/11694108.html