高并发下,spring框架中dbutils.QueryRunner可以单例存储

1:了解单例与多例的区别

单例:每次创建的对象是相同的,New对象只在堆中存放一份;

多例:每次创建的对象是不相同的,New对象在堆中存放N份;

2:了解子类对象中对父类成员变量的存储方式

子类对象先在堆中开辟一份空间,空间中存继承父类中的成员变量副本;

多个子类对象中存储的父类成员变量是不相同的;

3:了解QueryRunner类

 QueryRunner类无成员变量,所以可以通过单例的方式创建对象,是多线程安全的;

4:countDownLatch高并发验证

 @Test
    public void testfindAllAccount() throws InterruptedException {

        // 控制线程同步
        final CountDownLatch countDownLatch = new CountDownLatch(1000);
        final CountDownLatch countDownLatch2 = new CountDownLatch(1000);

        // 当前时间
        final Long startTime = System.currentTimeMillis();

        for(int i=0;i<1000;i++)
        {
           new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        // 阻塞等待其它线程
                        countDownLatch.await();

                        System.out.println("当前线程为"+Thread.currentThread().getName());
                        List<Account> allAccount = as.findAllAccount();

                        System.out.println(Thread.currentThread().getName()+"获取的数据长度:"+allAccount.size());
                        long endTime = System.currentTimeMillis();
                        System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms.");

                        countDownLatch2.countDown();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

           countDownLatch.countDown();
        }

        countDownLatch2.await();

    }

结果:

countDownLatch知识

附加知识点:spring框架中单例bean依赖注入多例bean无效

猜你喜欢

转载自blog.csdn.net/Growing_hacker/article/details/109009781