java - 多线程的 JDBC 问题

标签 java multithreading jdbc

我想运行新的连接,并且它在单独的线程上执行查询。我想通过初始化/连接到连接来启动线程,然后等待查询并在同一线程中运行它们。我的尝试是启动线程并初始化连接,然后暂停线程,仅在调用执行时才恢复。

private static synchronized boolean isActive()
{
    return active;
}

private static synchronized void makeActive()
{
    active = true;
}

    public void run()
    {  
        try
        {
            if(conn == null) 
            {
                onConnect();
            }

            synchronized(this)
            {
               while(!isActive())
                {
                    System.out.println(isActive());
                    wait();
                }

                System.out.println("exec");
                onExecute();
            }
        }



        catch(InterruptedException | SQLException e)
        {
                System.out.println("exception " + e.getMessage());
        }
}

onConnect 创建我的Connection 并调用onExecute 来执行查询。我在类外部调用一个查询来执行以下操作:

    public void execute(PreparedStatement statement, String query) throws SQLException
    {
        activeQuery               =   statement;
        makeActive();
}

目前,当我启动线程时,如果我不使用 join() ,我的 onConnect() 就会被跳过,并且当我确实让 onConnect 执行时,就会跳过 while 之后的 block (!isActive()) 不执行,所以我假设它总是在等待..

在此上下文中是否有更好的方法在 JDBC 中使用多线程,或者此代码中是否存在任何明显的错误?

最佳答案

看起来像经典的等待/通知对:

public void execute(PreparedStatement statement, String query) throws SQLException
{
    synchronized(this){
        activeQuery = statement;
        this.notify();
    }
}

和内部运行方法:

  while( some_finish_cond ) {
      synchronized(this){
         while(activeQuery==null){
             this.wait();
         }
         System.out.println("exec");
         onExecute();
         activeQuery = null;
      }                  
  }

关于java - 多线程的 JDBC 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002156/

相关文章:

python - 使用 ThreadPoolExecutor 时避免竞争条件

java - Tomcat 和数据库引用

java - 准备好的语句的性能调整

Java 文本文件 werid 输出格式

java - 使用 EclipseLink 获取数据库备份/转储

java - 在没有 poi 或 jxl 的情况下将 xls 文件转换为 pdf

java - java检查父目录是否存在

.NET 应用程序因 GC 线程死锁而挂起

java - 使用不同的线程迭代 ConcurrentSkipListSet 删除元素

java - 处理结果集中的空值