我有一个简单的程序。主要思想是我有一个存储在 MySQL 数据库中的名称列表,我想同时对这些名称执行一些操作,但是当然,每个线程应该以单独的名称工作。下一个线程应该使用前一个线程采用的下一个名称。我创建了线程池,在循环内创建了新线程,然后执行可运行的,以便执行对该名称的操作。在此示例中,该操作正在打印从 DB 中选择的名称。该程序正在从数据库中跳过一些名字,并将姓氏重复 6 次。我的程序有什么问题?我还是新手,请原谅我的错误。
这是主要功能:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static volatile ResultSet resultSet = null;
private static Statement statement = null;
public static void main(String[] args) throws SQLException
{
DBConnection.ConnectDB(); //connect to database
statement = DBConnection.con.createStatement();
resultSet = statement.executeQuery("select Name from schema.table1"); //select statement
String name = null;
// create ExecutorService to manage threads
ExecutorService threadExecutor = Executors.newFixedThreadPool(3 );
// create and name each runnable
while(resultSet.next())
{
name=resultSet.getString("Name");
MyRunnable task1 = new MyRunnable( name);
threadExecutor.execute( task1 );
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
threadExecutor.shutdown();
// Wait until all threads are finish
while (! threadExecutor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
和 MyRunnable 类:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
public class MyRunnable implements Runnable{
private static String nn;
MyRunnable (String ss) { synchronized (this) {
this.nn=ss;
}
}
public void run()
{
System.out.println("hello "+ nn);
}
}