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