我有一个数据库,其中有 100 个条目需要更新某些表列条目 这是动态需要更新的。
基本上他们从磁盘收集数据的所有 100 个条目 并更新数据库表。为了获取数据库/磁盘信息,他们 必须获得锁,并尝试直到在 while 循环中获得锁。 一旦获得锁,就只能将最新的磁盘信息更新到数据库。
我有一个以下伪代码,它基本上按顺序执行上述工作。 我想以多线程方式运行它们,以便可以完成并行工作。 你能指导我吗?我对java多线程程序完全陌生。
提前感谢您的帮助。
while(true)
{
for(int i=0,i<100;i++)
{
//Get the info from Disk
String diskInfo=getDiskInfo(i);
//Get the info from DB table
String dbInfo=getDBInfo(i);
if (! diskInfo.equals(dbInfo))
{
//Update DB with diskInfo
boolean status=UpdateDB(i);
}
}
sleep(2000);
}
//Get the info from Disk
public String getDiskInfo()
{
//Get the disk
//lock the disk wait if busy
while(true)
{
//get disk lock
sleep(2000);
}
//fetch data
String data = "test";
//unlock disk
return data;
}
public String getDBInfo()
{
//Get the DB
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
//fetch data
//select data from X;
String data = "test";
//unlock disk
return data;
}
public boolean UpdateDB()
{
//Get the DB
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
//fetch data
if(!getDiskInfo(),equals(getDBInfo())
{
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
status=UpdateDB();
}
else
{
//no update needed
status=false;
}
return status;
}
最佳答案
我不会编写代码来执行此操作。我会同步 Java 对象或使用数据库设施进行隔离来完成您想要的操作。
关于java多线程应用程序更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765305/