Java代码模拟并发测试工具——用代码的方式模拟并发

目录

CountDownLatch栅栏

Semaphore信号量

并发代码演示

并发代码线程安全提升


CountDownLatch栅栏

CountDownLatch的概念:

CountDownLatch是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。CountDownLatch的详细使用后续我们在深入讲解.


Semaphore信号量

Semaphore的概念

Semaphore是计数信号量。Semaphore管理一系列许可证。每个acquire方法阻塞,直到有一个许可证可以获得然后拿走一个许可证;每个release方法增加一个许可证,这可能会释放一个阻塞的acquire方法。然而,其实并没有实际的许可证这个对象,Semaphore只是维持了一个可获得许可证的数量。

并发代码演示

下面的代码既用了栅栏又用了信号量,许多简单的测试使用栅栏就够了。

@Slf4j
@NotThreadSafe
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++;
    }
}

并发代码线程安全提升

由线程不安全变为线程安全,仅使用栅栏的方式:

@Slf4j
public class ConcurencyTest {

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

    // 原子锁
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                countDownLatch.countDown();
                try {
                    countDownLatch.await();
                    add();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        try{
            //直到方法执行完成
            Thread.sleep(10000);
            executorService.shutdown();
            System.out.println(count);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }

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

}

或者这样写:

public class ConcurencyTest {

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

    // 原子锁
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws Exception {

        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for (int i = 0; i < clientTotal ; i++) {
            new Thread(()->{
                countDownLatch.countDown();
                try {
                    countDownLatch.await();
                    add();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
        try {
            Thread.sleep(10000);
            System.out.println(count);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值