繁体   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