[测试]并发模拟工具

Postman

Apache Bench

Jmeter

代码实现:CountDownLatch、Semaphore

CountDownLatch

/**
 * created by guanjian on 2020/12/28 11:19
 */
public class CountDownLatchTest {

    private static final CountDownLatch cdl = new CountDownLatch(3);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("开始");

        new Thread(() -> {
            try {
                System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
                Thread.sleep(1000);
                cdl.countDown();
                System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
                Thread.sleep(1000);
                cdl.countDown();
                System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
                Thread.sleep(1000);
                cdl.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        cdl.await(6000, TimeUnit.MILLISECONDS);
        print();
        System.out.println("结束");
    }

    private static void print() {
        System.out.println("执行了");
    }
}

Semaphore

/**
 * created by guanjian on 2020/12/28 15:31
 */
public class SemaphoreTest {

    //模拟汽车准乘人数
    private final static Semaphore semaphore = new Semaphore(5);

    //A旅行团人数5人
    private final static int A_NUMS = 5;
    //B旅行团人数5人
    private final static int B_NUMS = 5;

    public static void main(String[] args) throws InterruptedException {
        //A旅行团上车
        new Thread(() -> {
            IntStream.range(0,A_NUMS).forEach(x->{
                try {
                    System.out.format("当前汽车准乘人数=%s \n", semaphore.availablePermits());
                    semaphore.acquireUninterruptibly();
                    System.out.println("A旅行团上车1人 \n");
                    Thread.sleep(new Random().nextInt(3000));
                    System.out.format("剩余汽车准乘人数=%s \n", semaphore.availablePermits());
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }).start();

        //B旅行团上车
        new Thread(() -> {
            IntStream.range(0,B_NUMS).forEach(x->{
                try {
                    System.out.format("当前汽车准乘人数=%s \n", semaphore.availablePermits());
                    semaphore.acquireUninterruptibly();
                    System.out.println("B旅行团上车1人 \n");
                    Thread.sleep(new Random().nextInt(3000));
                    System.out.format("剩余汽车准乘人数=%s \n", semaphore.availablePermits());
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }).start();
    }
}
posted @ 2021-02-22 14:44  大摩羯先生  阅读(39)  评论(0编辑  收藏  举报