1

我有一个简单的程序。主要思想是我有一个存储在 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);
}
}
4

2 回答 2

6

这当然是一个问题。去除静电。

private static String nn;

变成

private String nn;
于 2012-07-04T21:03:37.757 回答
0

作为旁注,这个块:

while (! threadExecutor.isTerminated()) {
}

应该读:

while (! threadExecutor.isTerminated()) {
   try {
       threadExecutor.awaitTermination(1, TimeUnit.SECOND);
   }
   catch (InterruptedException e) {
        // you have to determine if someone can interrupt your wait
        // for the full termination of the executor, but most likely,
        // you'll do nothing here and swallow the exception, or rethrow
        // it in a RuntimeException
   }
}

你永远不应该像现在这样忙着等待。您将使用不必要的 CPU 周期,并占用池中实际线程的处理时间。

于 2012-07-04T23:40:43.823 回答