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

これは確かに 1 つの問題です。静電気を除去します。

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 に答える