I have a simple program. The main idea is that I have a list of names stored in MySQL database and I want to do some operations on these names concurrently, but of course, each thread should work in a separate name. The next thread should work on the next name that taken by the previous thread. I created thread pool, I create new threads inside the loop and then execute the runnable so the operations on that names performed. In this example, the operation is printing the name that is selected from DB. The program is skipping some names from the database, and repeated the last name 6 times. What is wrong in my program? I’m still new to threads, please excuse my mistakes.
This is the main function:
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");
}
}
And the MyRunnable class:
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);
}
}
This is certainly one issue. Remove the static.
becomes