gpt4 book ai didi

java - 尝试实现工作线程

转载 作者:行者123 更新时间:2023-12-01 14:01:04 25 4
gpt4 key购买 nike

我需要从表中读取数据并对每一行执行一些操作并将该行标记为已更新。我不想再次阅读更新的行。这是我计划用 ExecutorService 做的事情。这是正确的吗?

谢谢。

public class ScheduledDBPoll
{
public static void main(String args[])
{
ExecutorService service = Executors.newFixedThreadPool(10);
/* Connect to database. */
while (true)
{
/* Issue a select statment for un-updated rows. */
/* Get the primary key. */

service.submit(new Task(primaryKey)); /* Pass the primary key*/
try
{
Thread.sleep(3000); /* Sleep for 3 seconds. */
}
catch (InterruptedException ex)
{
Logger.getLogger(ScheduledDBPoll.class.getName()).log(Level.SEVERE, null, ex);
}
}
/* Close the connection here. */
}
}

final class Task implements Runnable
{
private int taskId;

public Task(int primayKey)
{
this.taskId = primayKey;
}

@Override
public void run()
{
try
{
/* Connect to database. */
/* Select the passed primary key row. */
/* Do some work, mark the row as updated. */
/* Close the connection here. */
}
catch (InterruptedException ex)
{
Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

我正在使用Firebird数据库,Firebird仅在连接级别是线程安全的。因此,我试图避免在同一连接上运行不同线程中的两个查询。我还忘记提及,上面的代码将作为 Windows 服务运行,因此它将始终寻找新插入的记录。

最佳答案

我会使用 ScheduledExecutorService 并且没有一个每三秒发送一次作业的线程。我还会保持连接打开,因为创建数据库连接非常慢。

所以我会像这样实现它

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Task(), 1, 1, TimeUnit.SECONDS);


final class Task implements Runnable {
private Connection connection;
private int taskId;

@Override
public void run() {
try {
if (!connectionIsOkay()) {
connectToDatabase();
taskId = selectUnUpdatedRow();
}
selectRowsToUpdate();
processRowsToUpdate();
markAsUpdated();

} catch (Exception ex) {
Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
}
}
// TODO find a more elegant way to close the connection when finished.
public void finalise() {
closeConnection();
}
}

关于java - 尝试实现工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346258/

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