私は簡単なプログラムを持っています。主なアイデアは、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);
}
}