Java和数据库中的多线程

时间:2012-07-04 20:58:26

标签: java mysql multithreading

我有一个简单的程序。主要的想法是我有一个存储在MySQL数据库中的名称列表,我想同时对这些名称进行一些操作,但当然,每个线程应该以一个单独的名称工作。下一个线程应该对前一个线程采用的下一个名称起作用。我创建了线程池,我在循环中创建新线程,然后执行runnable,以便执行对这些名称的操作。在此示例中,操作是打印从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);
}
}

2 个答案:

答案 0 :(得分:6)

这肯定是一个问题。删除静电。

private static String nn;

变为

private String nn;

答案 1 :(得分: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周期,并使处理时间远离池中的实际线程。