簡體   English   中英

Java中的多重處理-Drools和數據庫

[英]Multithreaing in java - drools and database

我對多線程還很陌生,並嘗試了一些方法來應用它,但是我還是有點堅持。

這是場景:使用流口水將規則應用於從db讀取的一組對象,然后將更新后的值寫回到db。

現在,我多次重復上述過程,所以我想在一個線程(主線程)中運行read + drool進程,在另一個線程中運行寫作部分。

所以我寫下面的代碼:

Thread thread = new Thread(new Runnable() 
{     public void run()
    { 
         try 
         {
    //writing the updated data in DB    
    aggregationDAO.updateCaseDetailsInOracle(queryList);
    } 
         catch (Exception e) {                              throw new RuntimeException();
    }
   }
});
    thread.start();

但是,我被困在這里。

首先,它期望我的queryList是最終的。

每當新的更新數據加載到同一變量中時,我都無法將其定為最終結果。

其次,

即使使程序運行多線程之后,運行時間也沒有任何改善。

有人可以告訴我我哪里錯了嗎?

您只使用自定義線程而不是'main',因此沒有任何改進。 您的示例中沒有“多”線程。

如果您想提高速度,則應同時運行多個線程。 使用某種線程池進行並發任務處理,您將得到即興的體驗。

另外,變量必須是最終變量,因為您正在創建匿名類-Runnable。 您應該創建新類,該類將實現Runnable並將變量傳遞給構造函數。

class QueryTask implements Runnable {
    private final List queryList;
    public QueryTask(List queryList) {
        this.queryList = queryList;
    }

    @Override
    public void run() {
        try { //writing the updated data in DB
            aggregationDAO.updateCaseDetailsInOracle(queryList);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}

用法:

final ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(new QueryTask(queryList.subList(0, 5)));
threadPool.submit(new QueryTask(queryList.subList(6, 10)));

這將同時處理您的queryList。

更新:

當您已經提交了所有任務后,可以關閉threadPool並等待所有任務完成。 之后,您無法添加任何新任務。

    threadPool.shutdown();
    try {
        threadPool.awaitTermination(10, TimeUnit.MINUTES);
    } catch (InterruptedException e) {               
        // Current thread was interrupted.
        final List<Runnable> runnables = threadPool.shutdownNow();
        System.out.println("Can't stop tasks: " + runnables.size());

        // Restore interrupted status.
        Thread.currentThread().interrupt();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM