gpt4 book ai didi

java - 线程执行未在循环中完成

转载 作者:行者123 更新时间:2023-11-29 08:59:46 24 4
gpt4 key购买 nike

我需要使用 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
}

}
}

问题是对于较大的 nos 这将无法正确执行。如果将每个线程的记录数增加 10000,进程运行时不会出现任何错误,但只会插入批处理的一部分。有什么想法吗?

最佳答案

这是错误的,请阅读评论。 :) 由于线程的一致性而离开它

您在线程中 hibernate 1000 毫秒。即 1 秒。

10000 次插入 = 10000 秒 = 166 分钟。

您允许线程池执行 15 分钟,然后将其关闭。

关于java - 线程执行未在循环中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18209998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com