鍍金池/ 問(wèn)答/Java  Linux/ Spring中多個(gè)線程調(diào)用Service中的方法出錯(cuò)

Spring中多個(gè)線程調(diào)用Service中的方法出錯(cuò)

service中入庫(kù)的方法,需要在多線程的情況下做測(cè)試,然后就開(kāi)啟兩個(gè)線程循環(huán)執(zhí)行service方法,但是出現(xiàn)了很多問(wèn)題,有以下幾種情況。

  1. 兩個(gè)線程都執(zhí)行到一半然后就報(bào)錯(cuò)終止,數(shù)據(jù)庫(kù)分別有幾條數(shù)據(jù)
  2. 兩個(gè)線程都只執(zhí)行一遍,數(shù)據(jù)庫(kù)分別有一條數(shù)據(jù)
  3. 數(shù)據(jù)庫(kù)沒(méi)有數(shù)據(jù)

相關(guān)代碼

 @Rollback(value = false)
    @Test
    public void test() throws Exception {
//        不開(kāi)啟線程,在主線程中執(zhí)行沒(méi)有問(wèn)題
//        for (int i = 0; i < 10; i++) {
//            normal(Thread.currentThread().getId(), i);
//        }

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    normal(Thread.currentThread().getId(), i);
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    normal(Thread.currentThread().getId(), i);
                }
            }
        });

        thread1.start();
        thread2.start();

    }

    public void normal(long id, int n) {
        auditLoggingService.insertAuditLogging("修改個(gè)人密碼成功" + id + "/" + n, 56, 6, 0,
                BaseConstants.AuditLoggingOperatorType.MODIFY, "修改個(gè)人密碼", "修改密碼", 0, "", "", "無(wú)", "", BaseConstants.UserInfo.USER_CAT_INNER, "yangyan", "");

    }

錯(cuò)誤信息

  1. 有時(shí)候可以成功執(zhí)行,沒(méi)有報(bào)錯(cuò)信息,但是數(shù)據(jù)庫(kù)沒(méi)有信息
  2. Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInter
回答
編輯回答
維她命

在測(cè)試類(lèi)中使用多線程,測(cè)試程序運(yùn)行完,線程就會(huì)隨之關(guān)閉.所以會(huì)出現(xiàn)這樣的問(wèn)題.
解決辦法是保持測(cè)試程序的持續(xù)運(yùn)行,比如sleep一段時(shí)間,讓線程先運(yùn)行完畢,或者在程序最后加上 System.in.read() 一直讀等待.

2017年7月20日 17:02