gpt4 book ai didi

Java 和数据库明显缓慢

转载 作者:行者123 更新时间:2023-11-29 06:05:34 26 4
gpt4 key购买 nike

我有一个java程序,它为从数据库读取的每个字段创建线程。我有很多字段(+10,000)。我遇到了速度明显缓慢的问题。除此之外,程序最后进入无限循环。即,有一个或多个线程永远不会结束,这使得循环无限。我尝试通过指定要读取的项目的编号 (PK) 来减少程序从 Java 代码内部读取的字段数量,如以下语句所示:

"select hName from schema.table where 
ID between 1 AND 200";

此更改后程序运行良好。我需要知道我应该做什么来解决这个问题。包含(where)等条件的语句会影响java程序的性能吗?如果我没有指定顺序或条件,但我的表中有主键,那么在没有任何条件的情况下创建语句是否是更好的选择?

其他类中还有一些其他插入语句。我确实同步那里的语句以避免两个线程具有相同的记录号。

synchronized (this) {
Query = " insert into schema.table values (default,?,?,?)";
Stmt = DBConnection.con.Statement(Query);
}

主函数中相关的代码是:

try {
ExecutorService threadExecutor = Executors.newFixedThreadPool(10);

while (resultSet.next()) {
name = resultSet.getString("hName");
MyRunnable worker = new Myrunnable(name);
threadExecutor.execute(worker);
Counter++;
}

//This never appears
System.out.println("End while with counter" + Counter);

threadExecutor.shutdown();
System.out.println("thread shutdown"); //this never appears

// Wait until all threads are finish
while (!threadExecutor.isTerminated()) {
threadExecutor.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("inside the thread termination loop."); //I have infinite loop

}

System.out.println("Finished all threads"); //never appears

} catch (Exception e) {
e.printStackTrace();
}

System.out.println("END MAIN");

DBConnection.con.close();

实现runnable的类在这里:

//The constructor
String threadName=null;
MyRunnable (String name) {
threadName=name;
}

public void run() {
myclass Obj=new myclass();
try {
Obj.myFunction(name);
} catch (Exception e) {
System.out.println("Got an Exception: "+e.getMessage());
}
System.out.println(" thread exiting" + threadName);
}

最佳答案

Q: I have a java program that creates thread for each field being read from the DB. I have a lot of fields (+10,000)

危险,威尔·罗宾逊!

设计阶段有人提出建议吗……这太疯狂了?不要这样做:)

Q: Does statements that contains conditions like, (where) affects the java program performance?

答:您是在问“带有“where”子句的 SQL 查询通常比直接转储整个表的性能更好吗?”

如果是这样:是的,“where”子句已知可以增强查询性能:)

关于Java 和数据库明显缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11656930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com