我需要使用 10 个线程将 50000 条记录插入数据库,每个线程 5000 条。前任。线程 1 将插入 1-5000,线程 2 将插入 5001-10000 等。
我已经使用 ExecutorService 来做到这一点。
代码
ExecutorService threadPool = Executors.newFixedThreadPool(10);
int i=0;
while(i<vVec.size())
{
if(i<vVec.size())
{
DBInsertDetail rrr = (DBInsertDetail)vVec.get(i);
TestThread t1 = new TestThread(rrr);
threadPool.execute(t1);
}
i++;
}
try {
threadPool.shutdown();
boolean bTermination = false;
while (true)
{
bTermination = threadPool.awaitTermination(15, TimeUnit.MINUTES);
if(!bTermination)
{
Log.debug("Awaiting completion of threads.");
}
else
{
Log.debug("Threads Completed."+iTermiVal);
break;
}
if(threadPool.isTerminated())
{
break;
}
}
} catch (Exception e) {}
测试线程类
public class TestThread implements Runnable
{
private volatile DBInsertDetail syncc;
public Thread1(DBInsertDetail syncc) {
this.syncc = syncc;
}
public void run() {
try
{ this.syncc.cardCreProcess(syncc.getIncre(),syncc.getStarterial(),syncc.getCurTblSeq());
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
DBInsertDetail 类
public class DBInsertDetail {
public void cardCreProcess(int iNum,int iCurrSerl,int iCurTblSeq)
{
int iCardCountTest = 0;
try
{
synchronized(this)
{
for (int i = 0; i < iNum; i++)
{
iCurrSerl++;
iCurTblSeq++;
iCardCountTest++;
CmnDet stkDet = new CmnDet();
Data crdData = new Data();
String sNo = crdData.getNextNo(pro, prof, sBranch, iCurrSerl);
stkDet.setNo(sNo);
stkDet.setCod(""+iCurTblSeq);
if (!stkDet.saveToDataBase(con))
{
sErrorMsg +="Error Occured" + "\n";
}
}
}
}catch(Exception ex)
{
ex.printStackTrace();
}
finally{
//commit and return connection
}
}
}
问题是对于较大的编号,这将无法正确执行。如果将每个线程的记录增加 10000 条,则进程运行时不会出现任何错误,但只插入批处理的一部分。任何想法?