java - 尝试实现工作线程

标签 java multithreading executorservice

我需要从表中读取数据并对每一行执行一些操作并将该行标记为已更新。我不想再次阅读更新的行。这是我计划用 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/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - 如何在java中保存ArrayList的元素?

java - 如何向调用者线程发出 ExecutorService 已完成任务的信号

java - Java 中这段代码中的 ExecutorService.submit 和 ExecutorService.execute 有什么区别?

java - @PreDestroy 没有被调用以用于 Runnable

java - 在用户输入java上暂停线程池

java - JDBC动态查询,如果不是-1则只将值写入字符串

java - 如何在 JAXB xml 中隐藏 "null=' true'"

c# - 如何在我的表单停止响应的情况下填充数据 GridView ?

c# - 在线程频繁写的情况下,哪种方式更好?