多線程查數(shù)據(jù)庫簡單案列

之前一直沒有用過多線程皮钠,這次贩绕,寫了一個(gè)多線程查詢數(shù)據(jù)庫的案列,并且比較一下多線程和單線程直接執(zhí)行的效率壶愤,體會(huì)一下多線程同步淑倾。數(shù)據(jù)庫中大概有1 W條數(shù)據(jù)。下面是核心代碼:

單線程一次查詢數(shù)據(jù)庫

TestServiceImpl

    @Override
    public List<Store> queryStoresInfo() {
        return testDao.queryStoresInfo();
    }

單線程For循環(huán)查詢數(shù)據(jù)庫

TestServiceImpl

    @Override
    public List<Store> queryStoresInfoByFor() {
        List<Store> lists = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            List<Store> list = testDao.queryStoresInfo();
            lists.addAll(list);
        }
        return lists;
    }

多線程查詢數(shù)據(jù)庫(使用join()進(jìn)行同步)

TestServiceImpl類(下面這個(gè)是我的一個(gè)錯(cuò)誤的做法

將join寫在循環(huán)內(nèi)征椒,實(shí)際本身還是一個(gè)串行的運(yùn)行過程娇哆。

    @Override
    public List<Store> queryStoresInfoByThread() throws InterruptedException {
        List<Store> lists = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new TestThread(lists));
            thread.start();
            thread.join();
        }
        return lists;
    }

TestServiceImpl類(正確的做法

    @Override
    public List<Store> queryStoresInfoByThread() throws InterruptedException {
        List<Store> lists = new ArrayList<>();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new TestThread(lists));
            thread.start();
            threads.add(thread);
        }
        for (Thread thread: threads){
            thread.join();
        }
        return lists;
    }

TestThread

public class TestThread implements Runnable {

    TestDao testDao = SpringBeanUtils.getBean(TestDao.class);

    private List<Store> stores;

    public TestThread(List<Store> stores) {
        this.stores = stores;
    }

    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() +" query data start...");
        List<Store> store = testDao.queryStoresInfo();
        synchronized (stores) {
            stores.addAll(store);
        }
        System.err.println(Thread.currentThread().getName() +" query data end...");
    }

}

多線程查詢數(shù)據(jù)庫(使用CountDownLatch進(jìn)行同步)

TestServiceImpl

    @Override
    public List<Store> queryStoresInfoByThread() throws InterruptedException {
        List<Store> lists = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new TestThread(lists, latch));
            thread.start();
        }
        latch.await();
        return lists;
    }

TestThread

public class TestThread implements Runnable {

    TestDao testDao = SpringBeanUtils.getBean(TestDao.class);

    private List<Store> stores;

    private CountDownLatch latch;

    public TestThread(List<Store> stores,CountDownLatch latch) {
        this.stores = stores;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() +" query data start...");
        List<Store> store = testDao.queryStoresInfo();
        synchronized (stores) {
            stores.addAll(store);
        }
        latch.countDown();
        System.err.println(Thread.currentThread().getName() +" query data end...");
    }

}

多線程查詢數(shù)據(jù)庫(使用線程池->CountDownLatch進(jìn)行同步)

TestServiceImpl

    @Override
    public List<Store> queryStoresInfoByThreadPool() {
        ExecutorService executorService = new ThreadPoolExecutor(5, 10, 1, TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(10));

        List<Store> resultList = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            executorService.execute(new TestThread(resultList,latch));
        }
        executorService.shutdown();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return resultList;
    }

TestThread

public class TestThread implements Runnable {

    TestDao testDao = SpringBeanUtils.getBean(TestDao.class);

    private List<Store> stores;

    private CountDownLatch latch;

    public TestThread(List<Store> stores,CountDownLatch latch) {
        this.stores = stores;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.err.println(Thread.currentThread().getName() +" query data start...");
        List<Store> store = testDao.queryStoresInfo();
        synchronized (stores) {
            stores.addAll(store);
        }
        latch.countDown();
        System.err.println(Thread.currentThread().getName() +" query data end...");
    }

}

運(yùn)行效率比較

single for Thread(join) Thread(latch) TheadPool
379 ms 1124 ms 544 ms 596 ms 507 ms
379 ms 1193 ms 500 ms 548 ms 493 ms
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市勃救,隨后出現(xiàn)的幾起案子碍讨,更是在濱河造成了極大的恐慌,老刑警劉巖蒙秒,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勃黍,死亡現(xiàn)場離奇詭異,居然都是意外死亡晕讲,警方通過查閱死者的電腦和手機(jī)覆获,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來益兄,“玉大人锻梳,你說我怎么就攤上這事【煌保” “怎么了疑枯?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蛔六。 經(jīng)常有香客問我荆永,道長,這世上最難降的妖魔是什么国章? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任具钥,我火速辦了婚禮,結(jié)果婚禮上液兽,老公的妹妹穿的比我還像新娘骂删。我一直安慰自己,他們只是感情好四啰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布宁玫。 她就那樣靜靜地躺著,像睡著了一般柑晒。 火紅的嫁衣襯著肌膚如雪欧瘪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天匙赞,我揣著相機(jī)與錄音佛掖,去河邊找鬼妖碉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛芥被,可吹牛的內(nèi)容都是我干的欧宜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拴魄,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼鱼鸠!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起羹铅,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎愉昆,沒想到半個(gè)月后职员,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡跛溉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年焊切,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片芳室。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡专肪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出堪侯,到底是詐尸還是另有隱情嚎尤,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布伍宦,位于F島的核電站芽死,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏次洼。R本人自食惡果不足惜关贵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望卖毁。 院中可真熱鬧揖曾,春花似錦、人聲如沸亥啦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽禁悠。三九已至念祭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間碍侦,已是汗流浹背粱坤。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國打工隶糕, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人站玄。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓枚驻,卻偏偏與公主長得像,于是被迫代替她去往敵國和親株旷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子再登,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355