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

查看:19
本文介绍了间隔运行 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天全站免登陆