我正在使用多线程的代码。相关代码的结构如下:
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();
run 函数肯定会结束。我的数据库中的姓氏执行所需的功能,其线程结束。
//The constructor
MyRunnable (String name) {
this.name=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" + this.name);
}
我的问题是我的程序正确执行了所有内容,除了在最后一个线程中,我看到带有数据库中姓氏的“线程退出”。但是线程执行器永远不会关闭,程序进入无限循环。
编辑
这是从数据库中提取名称的主要代码。
try {
st = DBConnection.con.createStatement();
resultSet = st.executeQuery("select hName from schema1.table1 where checked=1 order by hName");
} catch (Exception e) {
System.out.println("DB Error: " + e.getMessage());
}