我有一个 java 程序,它为从数据库中读取的每个字段创建线程。我有很多领域(+10,000)。我遇到了严重缓慢的问题。除此之外,程序最后进入一个无限循环。即,有一个或多个线程永远不会结束,这使得循环无限。我试图减少程序从 Java 代码中读取的字段数量,方法是指定要读取的项目的编号 (PK),如下面的语句所示:
"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);
}