间隔运行Java线程 [英] Running a Java Thread in intervals

查看:351
本文介绍了间隔运行Java线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要每10秒执行一次的线程。该线程包含对另一台服务器上的数据库的多次调用(12-15)。此外,它还可以访问大约3个文件。因此,将会有相当多的IO和网络开销。

I have a thread that needs to be executed every 10 seconds. This thread contains several calls (12 - 15) to a database on another server. Additionally, it also accesses around 3 files. Consequently, there will be quite a lot of IO and network overhead.

执行上述操作的最佳策略是什么?

What is the best strategy to perform the above?

一种方法是使用sleep方法和while循环,但那将是一个糟糕的设计。

One way would be to use the sleep method along with a while loop, but that would be a bad design.

在这种情况下,类似于Timer的类会有用吗?另外,最好是创建几个线程(一个用于IO,一个用于JDBC),而不是让它们在一个线程中运行?

Will a class similar to Timer be helpful in this case? Also, would it be better to create a couple of more threads (one for IO and one for JDBC), instead of having them run in one thread?

推荐答案

我发现 ScheduledExecutorService 是一种很好的方法。它可以说比 Timer 稍微复杂一些,但在交换时提供了更大的灵活性(例如,您可以选择使用单个线程或线程池;它只需要单独的单元毫秒)。

I find that a ScheduledExecutorService is an excellent way to do this. It is arguably slightly more complex than a Timer, but gives more flexibility in exchange (e.g. you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds).

ScheduledExecutorService executor =
    Executors.newSingleThreadScheduledExecutor();

Runnable periodicTask = new Runnable() {
    public void run() {
        // Invoke method(s) to do the work
        doPeriodicWork();
    }
};

executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);

这篇关于间隔运行Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆